XPath съдържа: текст, следващ брат и предшественик в Selenium
🚀 Интелигентно обобщение
XPath съдържа, брат/сестра и прародител в Selenium позволяват прецизна идентификация на уеб елементи, използвайки структурирани взаимоотношения и текстови модели. Тези XPath функции подобряват надеждността, гъвкавостта и поддръжката на автоматизацията в сложни DOM йерархии.
Какво съдържа XPath?
XPath съдържа е функция в XPath израз, която се използва за търсене на уеб елементи, съдържащи определен текст. Можем да извлечем всички елементи, които съответстват на дадената текстова стойност, използвайки функцията XPath contains() в цялата уеб страница. Contains в XPath има възможността да намери елемент с частичен текст.
Пример – съдържа текст
Тук търсим котва .съдържа текст като "SAP М'.
"//h4/a[contains(text(),'SAP M')]"
ЗАБЕЛЕЖКА: Можете да практикувате следното XPath упражнение върху това https://demo.guru99.com/test/selenium-xpath.html
Ако е прост XPath не може да намери сложен уеб елемент за нашия тестов скрипт, трябва да използваме функциите от библиотеката XPath 1.0. С комбинацията от тези функции можем да създадем по-специфичен XPath.
👉 Запишете се за безплатен концерт Selenium Тест проект
Следване на брат или сестра в XPath
A Брат и сестра в Selenium Уебдрайвер е функция, използвана за извличане на уеб елемент, който е „sibling“ на родителския елемент. Ако родителският елемент е известен, тогава уеб елементът може лесно да бъде намерен или локализиран, което може да се направи чрез атрибута „sibling“ на XPath израза в Selenium WebDriver.
Пример за брат в XPath:
Тук, въз основа на родствения елемент на 'a', намираме 'h4'
"//div[@class='canvas- graph']//a[@href='/accounting.html'][i[@class='icon-usd']]/following-sibling::h4"
прародителЗа да намерим елемент въз основа на родителския елемент, можем да използваме атрибута ancestry на XPath.
Нека разберем тези 3 функции, използвайки пример –
Стъпки на теста:
Забележка: От датата на създаване на урока, началната страница на Guru99 е актуализирана, така че използвайте демо сайта, за да провеждате тестове.
- Отиди https://demo.guru99.com/test/guru99home/
- В секцията „Няколко от най-популярните ни курсове“ търсете всички уеб елементи, които са братя и сестри на уеб елемент, чийто текст е „SELENIUM“.
- Ще намерим елементи, използвайки XPath функциите text contains, ancestor и sibling.
ИЗПОЛЗВАНЕ Съдържа Text и XPath Sibling
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
// If you prefer WebDriverManager (optional):
// import io.github.bonigarcia.wdm.WebDriverManager;
public class SiblingAndParentInXpath_Chrome {
@Test
public void testSiblingAndParentInXpath() {
// === Option A: Use local ChromeDriver binary path ===
// Update this path to your chromedriver location:
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
// === Option B: Use WebDriverManager (uncomment next line and remove Option A lines) ===
// WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
// Add any flags you need, e.g. headless:
// options.addArguments("--headless=new");
WebDriver driver = new ChromeDriver(options);
try {
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
driver.get("https://demo.guru99.com/test/guru99home/");
// Find all siblings (divs) next to the 'SELENIUM' tile within
// the "A few of our most popular courses" section.
// Steps encoded in XPath:
// 1) Locate the H2 that contains the section title
// 2) Move to its parent DIV
// 3) Inside it, locate the link with text 'SELENIUM'
// 4) From the SELENIUM tile's parent DIV, get following sibling tiles
List<WebElement> dateBox = driver.findElements(By.xpath(
"//h2[contains(., 'A few of our most popular courses')]/parent::div" +
"//a[normalize-space(.)='SELENIUM']/parent::div" +
"/following-sibling::div[contains(@class,'rt-grid-2')]"
));
// Print the text of each sibling element
for (WebElement el : dateBox) {
System.out.println(el.getText());
}
} finally {
driver.quit();
}
}
}
Изходът ще бъде като:
Предшественик на XPath в Selenium
Предшественик на XPath в Selenium е функция, използвана за намиране на предшественика на специфичен елемент на посочения слой. Нивото на предшественика, което ще бъде върнато, или нивото на предшественика спрямо нивото на члена може да бъде изрично зададено. Тя връща броя на йерархичните стъпки от предшественика, локализирайки посочения предшественик, който потребителят иска.
Да предположим, че трябва да търсим всички елементи в секцията „Популярни курсове“ с помощта на предшественика на котвата, чийто текст е „SELENIUM“.
Тук нашата xpath заявка ще бъде като
"//div[.//a[text()='SELENIUM']]/ancestor::div[@class='rt-grid-2 rt-omega']/following-sibling::div"
Пълен код
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
public class AncestorInXpath_Chrome {
@Test
public void testAncestorInXpath() {
// Set path to your ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
WebDriver driver = new ChromeDriver(options);
try {
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
driver.get("https://demo.guru99.com/test/guru99home/");
// Search all elements in 'Popular course' section
// using the ancestor of the 'SELENIUM' link
List <WebElement> dateBox = driver.findElements(
By.xpath("//div[.//a[text()='SELENIUM']]/ancestor::div[@class='rt-grid-2 rt-omega']/following-sibling::div")
);
// Print all sibling elements of the 'SELENIUM' tile
for (WebElement element : dateBox) {
System.out.println(element.getText());
}
} finally {
driver.quit();
}
}
}
Резултатът ще изглежда като-
Използване на И и ИЛИ
Чрез използване на AND и OR можете да поставите 2 условия в нашия XPath израз.
- В случай на И, и двете условия трябва да са верни, само тогава се намира елементът.
- В случай на ИЛИ, едно от двете условия трябва да е вярно, само тогава се намира елементът.
Тук нашата XPath заявка ще бъде така
Xpath=//*[@type='submit' OR @name='btnReset']
Xpath=//input[@type='submit' and @name='btnLogin']
Стъпки на теста:
- Отиди https://demo.guru99.com/v1/
- В този раздел ще използваме горния демонстрационен сайт, за да търсим елементи с различни функции на XPath.
Ще намерите елемент с помощта на И и ИЛИ, родител, започва с и XPath оси
И ИЛИ Пример
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class AND_OR {
public static void main(String[] args) {
WebDriver driver;
WebElement w,x;
System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
driver= new ChromeDriver();
// Launch the application
driver.get("https://www.guru99.com/");
//Search element using OR in the xpath
w=driver.findElement(By.xpath("//*[@type='submit' OR @name='btnReset']"));
//Print the text of the element
System.out.println(w.getText());
//Search element using AND in the xpath
x=driver.findElement(By.xpath("//input[@type='submit' and @name='btnLogin']"));
//Print the text of the searched element
System.out.println(x.getText());
//Close the browser
driver.quit();
}
}
XPath родител в Selenium
Родител в Selenium е метод, използван за извличане на родителския възел на текущо избрания възел в уеб страницата. Той е много полезен в ситуации, когато изберете елемент и трябва да получите родителския елемент, използвайки XPath. Този метод се използва и за получаване на родителския елемент на родителя.
Тук нашата XPath заявка ще бъде така
Xpath=//*[@id='rt-feature']//parent::div
XPath с помощта на родител
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Parent {
public static void main(String[] args) {
WebDriver driver;
WebElement w;
System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
driver= new ChromeDriver();
// Launch the application
driver.get("https://www.guru99.com/");
//Search the element by using PARENT
w=driver.findElement(By.xpath("//*[@id='rt-feature']//parent::div"));
//Print the text of the searched element
System.out.println(w.getText());
//Close the browser
driver.quit();
}
}
Започва-с
Използвайки функцията Starts-with, можете да намерите елемента, чийто атрибут се променя динамично при обновяване или други операции като щракване, изпращане и др.
Тук нашата XPath заявка ще бъде като
Xpath=//label[starts-with(@id,'message')]
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class StartsWith {
public static void main(String[] args) {
WebDriver driver;
WebElement w;
System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
driver= new ChromeDriver();
// Launch the application
driver.get("https://www.guru99.com/");
//Search the element by using starts-with
w=driver.findElement(By.xpath("//label[starts-with(@id,'message')]"));
//Print the text of the searched element
System.out.println(w.getText());
//Close the browser
driver.quit();
}
}
Xpath оси
С помощта на XPath оси можете да намерите динамичните и много сложни елементи на уеб страница. XPath осите съдържат няколко метода за намиране на елемент. Тук ще обсъдим няколко метода.
следващ: Тази функция ще върне непосредствения елемент на конкретния компонент.
Тук нашата XPath заявка ще бъде като
Xpath=//*[@type='text']//following::input

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Following {
public static void main(String[] args) {
WebDriver driver;
WebElement w;
System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
driver= new ChromeDriver();
// Launch the application
driver.get("https://www.guru99.com/");
//Search the element by using Following method
w=driver.findElement(By.xpath("//*[@type='text']//following::input"));
//Print the text of the searched element
System.out.println(w.getText());
//Close the browser
driver.quit();
}
}
Предходен: Тази функция ще върне предходния елемент на конкретния елемент.
Тук нашата XPath заявка ще бъде като
Xpath= //*[@type='submit']//preceding::input
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Preceding {
public static void main(String[] args) {
WebDriver driver;
WebElement w;
System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
driver= new ChromeDriver();
// Launch the application
driver.get("https://www.guru99.com/");
//Search the element by using preceding method
w=driver.findElement(By.xpath("//*[@type='submit']//preceding::input"));
//Print the searched element
System.out.println(w.getText());
//Close the browser
driver.quit();
}
}
d) Потомък: Тази функция ще върне наследствения елемент на конкретния елемент.
Тук нашата XPath заявка ще бъде като
Xpath= //*[@id='rt-feature']//descendant::a
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Descendant {
public static void main(String[] args) {
WebDriver driver;
WebElement w;
System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
driver= new ChromeDriver();
// Launch the application
driver.get("https://www.guru99.com/");
//Search the element by using descendant method
w=driver.findElement(By.xpath("//*[@id='rt-feature']//descendant::a"));
//Print the searched element
System.out.println(w.getText());
//Close the browser
driver.quit();
}
}










