XPath conține: text, următorul frate și strămoș în Selenium
🚀 Rezumat inteligent
XPath conține, rudă și strămoș în Selenium permit identificarea precisă a elementelor web folosind relații structurate și modele de text. Aceste funcții XPath îmbunătățesc fiabilitatea, flexibilitatea și mentenabilitatea automatizării în ierarhii DOM complexe.
Ce este XPath Contains?
XPath conține este o funcție în cadrul unei expresii XPath, care este utilizată pentru a căuta elementele web care conțin un anumit text. Putem extractoate elementele care corespund valorii text date folosind funcția XPath contains() în întreaga pagină web. Funcția Contains din XPath are capacitatea de a găsi elementul cu text parțial.
Exemplu – conține text
Aici căutăm o ancoră .contains text ca „SAP M'.
"//h4/a[contains(text(),'SAP M')]"
NOTĂ: Puteți exersa următorul exercițiu XPath în acest sens https://demo.guru99.com/test/selenium-xpath.html
Dacă un simplu XPath Dacă nu reușește să găsească un element web complicat pentru scriptul nostru de testare, trebuie să folosim funcțiile din biblioteca XPath 1.0. Prin combinarea acestor funcții, putem crea un XPath mai specific.
👉 Înscrie-te pentru Live Gratuit Selenium Proiect de testare
Urmărirea fratelui în XPath
A Frate înăuntru Selenium Webdriver este o funcție utilizată pentru a prelua un element web care este rudă cu elementul părinte. Dacă elementul părinte este cunoscut, atunci elementul web poate fi găsit sau localizat cu ușurință, ceea ce poate utiliza atributul rudă al expresiei XPath din Selenium WebDriver.
Frate în XPath Exemplu:
Aici, pe baza elementului frate al lui „a”, găsim „h4”
"//div[@class='canvas- graph']//a[@href='/accounting.html'][i[@class='icon-usd']]/following-sibling::h4"
StrămoşPentru a găsi un element pe baza elementului părinte, putem folosi atributul ancester al XPath.
Să înțelegem aceste 3 funcții folosind un exemplu –
Pașii de testare:
Notă: De la data creării tutorialului, pagina principală a GuruVersiunea 99 a fost actualizată, așa că folosiți site-ul demo pentru a rula teste.
- Accesează https://demo.guru99.com/test/guru99home/
- În secțiunea „Câteva dintre cele mai populare cursuri ale noastre”, căutați toate elementele web care sunt rude ale unui element web al cărui text este „SELENIUM”.
- Vom găsi elemente folosind funcțiile XPath de tip „contains”, „ancester” și „sibling”.
UTILIZARE Conține text și XPath Frate
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();
}
}
}
Ieșirea va fi ca:
XPath Ancestor în Selenium
XPath Ancestor în Selenium este o funcție utilizată pentru a găsi strămoșul unui anumit element la stratul specificat. Nivelul strămoșului care va fi returnat sau nivelul strămoșului relativ la nivelul membrului poate fi specificat explicit. Returnează numărul de pași ierarhici de la strămoș, localizând strămoșul specificat dorit de utilizator.
Acum, să presupunem că trebuie să căutăm toate elementele din secțiunea „Curs popular” cu ajutorul strămoșului ancorei al cărei text este „SELENIU”.
Aici interogarea noastră xpath va fi ca
"//div[.//a[text()='SELENIUM']]/ancestor::div[@class='rt-grid-2 rt-omega']/following-sibling::div"
Completa 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();
}
}
}
Ieșirea va arăta ca...
Folosind AND și SAU
Folosind AND și OR, puteți pune 2 condiții în expresia noastră XPath.
- În cazul operației AND, ambele condiții ar trebui să fie adevărate, numai atunci găsește elementul.
- În cazul operației SAU, oricare dintre cele 2 condiții trebuie să fie adevărată, numai atunci găsește elementul.
Aici, interogarea noastră XPath va fi de genul:
Xpath=//*[@type='submit' OR @name='btnReset']
Xpath=//input[@type='submit' and @name='btnLogin']
Pașii de testare:
- Accesează https://demo.guru99.com/v1/
- În această secțiune, vom folosi site-ul demonstrativ de mai sus pentru a căuta elemente cu diferite funcții XPath.
Veți găsi un element folosind axele AND și SAU, părinte, începe cu și XPath
ȘI SAU Exemplu
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 Parent în Selenium
Părinte în Selenium este o metodă utilizată pentru a recupera nodul părinte al nodului curent selectat în pagina web. Este foarte utilă în situațiile în care selectați un element și trebuie să obțineți elementul părinte folosind XPath. Această metodă este utilizată și pentru a obține părintele nodului părinte.
Aici, interogarea noastră XPath va fi de genul:
Xpath=//*[@id='rt-feature']//parent::div
XPath folosind Parent
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();
}
}
Incepe cu
Folosind funcția Starts-with, puteți găsi elementul al cărui atribut se modifică dinamic la reîmprospătare sau la alte operațiuni precum clic, trimitere etc.
Aici interogarea noastră XPath va fi ca
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();
}
}
Axele Xpath
Folosind axele XPath, puteți găsi elementele dinamice și foarte complexe pe o pagină web. Axele XPath conțin mai multe metode de a găsi un element. Aici, vom discuta câteva metode.
următor: Această funcție va returna elementul imediat al componentei particulare.
Aici interogarea noastră XPath va fi ca
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();
}
}
Precedent: Această funcție va returna elementul precedent al elementului particular.
Aici interogarea noastră XPath va fi ca
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) Descendentă: Această funcție va returna elementul descendent al unui anumit element.
Aici interogarea noastră XPath va fi ca
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();
}
}










