XPath zawiera: tekst, następujące elementy rodzeństwa i przodka w Selenium
🚀 Inteligentne podsumowanie
XPath zawiera, rodzeństwo i przodka w Selenium Umożliwiają precyzyjną identyfikację elementów internetowych za pomocą strukturalnych relacji i wzorców tekstowych. Te funkcje XPath zwiększają niezawodność, elastyczność i łatwość utrzymania automatyzacji w złożonych hierarchiach DOM.
Co zawiera XPath?
XPath zawiera to funkcja w wyrażeniu XPath, która służy do wyszukiwania elementów internetowych zawierających określony tekst. Możemy np.tracWszystkie elementy pasujące do podanej wartości tekstowej są wyszukiwane za pomocą funkcji XPath contains() na całej stronie internetowej. Funkcja Contains w XPath umożliwia znalezienie elementu z fragmentem tekstu.
Przykład – zawiera tekst
Tutaj szukamy kotwicy zawierającej tekst „SAP M'.
"//h4/a[contains(text(),'SAP M')]"
UWAGA: Możesz przećwiczyć następujące ćwiczenie XPath https://demo.guru99.com/test/selenium-xpath.html
Jeśli prosty XPath Jeśli nie możemy znaleźć skomplikowanego elementu webowego dla naszego skryptu testowego, musimy skorzystać z funkcji z biblioteki XPath 1.0. Dzięki połączeniu tych funkcji możemy stworzyć bardziej szczegółową ścieżkę XPath.
👉 Zarejestruj się bezpłatnie na żywo Selenium Projekt testowy
Obserwowanie rodzeństwa w XPath
A Rodzeństwo w Selenium Sterownik internetowy to funkcja służąca do pobierania elementu sieciowego, który jest elementem siostrzanym elementu nadrzędnego. Jeśli element nadrzędny jest znany, element sieciowy można łatwo znaleźć lub zlokalizować, korzystając z atrybutu sibling wyrażenia XPath w Selenium Sterownik sieciowy.
Przykład rodzeństwa w XPath:
Tutaj, na podstawie elementu siostrzanego „a”, znajdujemy „h4”
"//div[@class='canvas- graph']//a[@href='/accounting.html'][i[@class='icon-usd']]/following-sibling::h4"
PrzodekAby znaleźć element na podstawie elementu nadrzędnego, możemy wykorzystać atrybut ancestor XPath.
Zrozumiemy te 3 funkcje na przykładzie –
Kroki testowe:
Uwaga: Od daty utworzenia samouczka, strona główna GuruWersja 99 została zaktualizowana, więc do przeprowadzania testów użyj witryny demonstracyjnej
- Iść do https://demo.guru99.com/test/guru99home/
- W sekcji „Kilka naszych najpopularniejszych kursów” wyszukaj wszystkie elementy sieci Web, które są pokrewne elementowi sieci Web, którego tekstem jest „SELENIUM”
- Znajdziemy elementy korzystając z funkcji tekstu XPath contains, przodka i elementów rodzeństwa.
USING Zawiera tekst i rodzeństwo 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();
}
}
}
Dane wyjściowe będą takie:
Przodek XPath w Selenium
Przodek XPath w Selenium Funkcja ta służy do wyszukiwania przodka określonego elementu na określonej warstwie. Poziom przodka, który ma zostać zwrócony, lub poziom przodka względem poziomu elementu może być określony jawnie. Funkcja zwraca liczbę kroków hierarchicznych od przodka, lokalizując wskazanego przodka, którego szuka użytkownik.
Załóżmy teraz, że musimy przeszukać wszystkie elementy w sekcji „Popularne kursy” za pomocą przodka kotwicy, której tekstem jest „SELENIUM”
Tutaj będzie wyglądało nasze zapytanie xpath
"//div[.//a[text()='SELENIUM']]/ancestor::div[@class='rt-grid-2 rt-omega']/following-sibling::div"
Absolutna 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();
}
}
}
Dane wyjściowe będą wyglądać następująco:
Używanie AND i OR
Używając AND i OR, możesz umieścić 2 warunki w wyrażeniu XPath.
- W przypadku AND obydwa warunki muszą być prawdziwe, dopiero wtedy element zostanie znaleziony.
- W przypadku OR, dowolny z dwóch warunków musi być spełniony, dopiero wtedy element zostanie znaleziony.
Tutaj nasze zapytanie XPath będzie wyglądać następująco:
Xpath=//*[@type='submit' OR @name='btnReset']
Xpath=//input[@type='submit' and @name='btnLogin']
Kroki testowe:
- Iść do https://demo.guru99.com/v1/
- W tej sekcji wykorzystamy powyższą witrynę demonstracyjną do wyszukania elementów z różnymi funkcjami XPath.
Element znajdziesz za pomocą osi AND i OR, rodzica, początku i XPath
ORAZ LUB Przykład
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();
}
}
Rodzic XPath w Selenium
Rodzic w Selenium to metoda używana do pobierania węzła nadrzędnego aktualnie wybranego węzła na stronie internetowej. Jest bardzo przydatna w sytuacjach, gdy wybierasz element i musisz pobrać element nadrzędny za pomocą XPath. Ta metoda służy również do pobierania elementu nadrzędnego elementu nadrzędnego.
Tutaj nasze zapytanie XPath będzie wyglądać następująco:
Xpath=//*[@id='rt-feature']//parent::div
XPath przy użyciu rodzica
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();
}
}
Zaczynać z
Korzystając z funkcji Starts-with, możesz znaleźć element, którego atrybut zmienia się dynamicznie podczas odświeżenia lub innych operacji, takich jak kliknięcie, przesłanie itp.
Tutaj będzie wyglądało nasze zapytanie 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();
}
}
Osie Xpath
Używając osi XPath, możesz znaleźć dynamiczne i bardzo złożone elementy na stronie internetowej. Osie XPath zawierają kilka metod znajdowania elementu. Tutaj omówimy kilka metod.
następujący: Ta funkcja zwróci bezpośredni element konkretnego komponentu.
Tutaj będzie wyglądało nasze zapytanie 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();
}
}
Poprzedzający: Ta funkcja zwróci element poprzedzający konkretnego elementu.
Tutaj będzie wyglądało nasze zapytanie 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) Malejąco: Ta funkcja zwróci element potomny określonego elementu.
Tutaj będzie wyglądało nasze zapytanie 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();
}
}










