Если простой XPath не может найти сложный веб-элемент для нашего тестового скрипта, нам нужно использовать функции из библиотеки XPath 1.0. С помощью комбинации этих функций мы можем создать более конкретный XPath. Давайте обсудим 3 такие функции —
Давайте изучим их подробно —
Содержит
Используя функцию «содержит» в XPath, мы можем извлечь все элементы, которые соответствуют определенному текстовому значению.
Ex. Здесь мы ищем привязку. Содержит текст как «SAP M».
"//h4/a[contains(text(),'SAP M')]"
родной брат
Используя ключевое слово sibling, мы можем получить веб-элемент, связанный с каким-либо другим элементом.
Пример: здесь на основе родственного элемента ‘a’ мы находим ‘h4’
"//div[@class='canvas- graph']//a[@href='/accounting.html'][i[@class='icon-usd']]/following-sibling::h4"
Ancestor : чтобы найти элемент на основе родительского элемента, мы можем использовать атрибут ancestor в XPath.
Давайте разберемся с этими тремя функциями на примере:
Тестовые шаги
Примечание. Со времени создания учебного пособия домашняя страница Guru99 была обновлена, поэтому вместо этого используйте демонстрационный сайт для запуска тестов.
- Перейдите на http://demo.guru99.com/test/guru99home/
- В разделе «Некоторые из наших самых популярных курсов» найдите все веб-элементы, которые являются родственными элементами веб-элемента с текстом «SELENIUM».
- Мы найдем элемент, используя функции contains, ancestor и sibling
ИСПОЛЬЗОВАНИЕ Содержит и родного брата
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class SiblingAndParentInXpath {
@Test
public void testSiblingAndParentInXpath(){
WebDriver driver;
String driverPath = "C:\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", driverPath);
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://demo.guru99.com/test/guru99home/");
//Search element inside 'Popular course' which are sibling of control 'SELENIUM' ,Here first we will find a h2 whose text is ''A few of our most popular courses' ,then we move to its parent element which is a 'div' , inside this div we will find a link whose text is 'SELENIUM' then at last we will find all of the sibling elements of this link('SELENIUM')
List <WebElement> dateBox = driver.findElements(By.xpath("//h2[contains(text(),'A few of our most popular courses')]/parent::div//div[//a[text()='SELENIUM']]/following-sibling::div[@class='rt-grid-2 rt-omega']"));
//Print all the which are sibling of the the element named as 'SELENIUM' in 'Popular course'
for (WebElement webElement : dateBox) {
System.out.println(webElement.getText());
}
driver.close();
}
}
Выход будет как:
Функция предка
Мы можем достичь той же функциональности с помощью функции «предок».
Теперь предположим, что нам нужно найти все элементы в разделе «Популярный курс» с помощью предка якоря, текст которого «SELENIUM»
Здесь наш запрос xpath будет похож
"//div[.//a[text()='SELENIUM']]/ancestor::div[@class='rt-grid-2 rt-omega']/following-sibling::div"
Полный код
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class AncestorInXpath{
@Test
public void testAncestorInXpath(){
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://demo.guru99.com/test/guru99home/");
//Search All elements in 'Popular course' section
//with the help of ancestor of the anchor whose text is 'SELENIUM'
List <WebElement> dateBox = driver.findElements(By.xpath("//div[.//a[text()='SELENIUM']]/ancestor::div[@class='rt-grid-2 rt-omega']/following-sibling::div"));
//Print all the which are sibling of the element named as 'SELENIUM' in 'Popular course'
for (WebElement webElement : dateBox) {
System.out.println(webElement.getText());
}
driver.quit();
}
}
Вывод будет выглядеть как
Использование AND и OR
Используя AND и OR, вы можете поместить 2 условия в наше выражение XPath.
- В случае AND оба условия должны быть выполнены, тогда только он находит элемент.
- В случае ИЛИ любое из 2 условий должно быть выполнено, тогда только он находит элемент.
Здесь наш XPath-запрос будет похож
Xpath=//*[@type='submit' OR @name='btnReset']
Xpath=//input[@type='submit' and @name='btnLogin']
Тестовые шаги:
- Перейти на http://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();
}
}
родитель
Используя Parent, вы можете найти родительский узел текущего узла на веб-странице.
Здесь наш XPath-запрос будет похож
Xpath=//*[@id='rt-feature']//parent::div
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();
}
}
Начинается с
Используя функцию «Начинается с», вы можете найти элемент, атрибут которого динамически изменяется при обновлении или других операциях, таких как нажатие, отправка и т. Д.
Здесь наш 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();
}
}
Резюме
- В некоторых ситуациях обычный XPath не может быть использован для поиска элемента. В такой ситуации нам нужны разные функции из запроса xpath.
- Есть некоторые важные функции XPath, такие как содержит, родитель, предки, последующий брат и т. Д.
- С помощью этих функций вы можете создавать сложные выражения XPath.











