XPath содержит: текст, следующий за родственным элементом и предком в Selenium
🚀 Умное резюме
XPath содержит, родственный и предковый элементы в Selenium Обеспечивают точную идентификацию веб-элементов с помощью структурированных взаимосвязей и текстовых шаблонов. Эти функции XPath повышают надежность, гибкость и удобство автоматизации в сложных иерархиях DOM.
Что содержит XPath?
XPath содержит Это функция внутри выражения XPath, которая используется для поиска веб-элементов, содержащих определенный текст. Мы можем использовать следующие выражения:tracФункция `contains()` в XPath позволяет найти все элементы, соответствующие заданному текстовому значению, на всей веб-странице. Функция `contains` в XPath позволяет найти элемент с неполным текстом.
Пример – содержит текст
Здесь мы ищем якорь .содержит текст как 'SAP М'.
"//h4/a[contains(text(),'SAP M')]"
ПРИМЕЧАНИЕ. На этом примере вы можете попрактиковаться в следующем упражнении XPath. https://demo.guru99.com/test/selenium-xpath.html
Если простой XPath Не удалось найти сложный веб-элемент для нашего тестового скрипта, нам нужно использовать функции из библиотеки XPath 1.0. Комбинируя эти функции, мы можем создать более специфичный XPath.
👉 Зарегистрируйтесь на бесплатный Live Selenium Тестовый проект
Следование за братом в XPath
A Брат в Selenium Вебдрайвер — это функция, используемая для извлечения веб-элемента, являющегося родственным родительскому элементу. Если родительский элемент известен, то веб-элемент можно легко найти, используя атрибут sibling выражения XPath в Selenium ВебДрайвер.
Брат в примере XPath:
Здесь, на основе родственного элемента «а», мы находим «h4».
"//div[@class='canvas- graph']//a[@href='/accounting.html'][i[@class='icon-usd']]/following-sibling::h4"
предок: Чтобы найти элемент на основе родительского элемента, мы можем использовать атрибут ancestor XPath.
Давайте разберем эти 3 функции на примере:
Этапы тестирования:
Примечание: С момента создания данного руководства, главная страница GuruВерсия 99 обновлена, поэтому для запуска тестов используйте демонстрационный сайт.
- Перейдите на https://demo.guru99.com/test/guru99home/
- В разделе «Некоторые из наших самых популярных курсов» найдите все веб-элементы, которые являются родственными по отношению к веб-элементу с текстом «SELENIUM».
- Мы найдем элементы, используя функции XPath text contain, ancestor и sibling.
USING Содержит текст и родственный XPath
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 — это функция, используемая для поиска предка определенного элемента на указанном уровне. Уровень возвращаемого предка или уровень предка относительно уровня элемента можно указать явно. Функция возвращает количество иерархических шагов от предка, находя нужного пользователю предка.
Теперь предположим, что нам нужно выполнить поиск по всем элементам в разделе «Популярный курс» с помощью предка якоря, текст которого — «СЕЛЕН».
Здесь наш запрос xpath будет выглядеть так:
"//div[.//a[text()='SELENIUM']]/ancestor::div[@class='rt-grid-2 rt-omega']/following-sibling::div"
Завершенный Code
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();
}
}
}
Вывод будет выглядеть так:
Использование И и ИЛИ
Используя И и ИЛИ, вы можете добавить 2 условия в наше выражение XPath.
- В случае AND оба условия должны быть истинными, только тогда он найдет элемент.
- В случае ИЛИ любое из двух условий должно быть истинным, только тогда элемент будет найден.
Здесь наш запрос XPath будет выглядеть так:
Xpath=//*[@type='submit' OR @name='btnReset']
Xpath=//input[@type='submit' and @name='btnLogin']
Этапы тестирования:
- Перейдите на https://demo.guru99.com/v1/
- В этом разделе мы будем использовать вышеуказанный демонстрационный сайт для поиска элементов с различными функциями XPath.
Вы найдете элемент, используя оси AND и OR, родительский элемент, начало с и 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();
}
}










