XPath contient : du texte, le frère ou la sœur suivant et l'ancêtre dans Selenium
🚀 Résumé intelligent
XPath contient, frère et ancêtre dans Selenium Permettent une identification précise des éléments web grâce à l'utilisation de relations structurées et de modèles textuels. Ces fonctions XPath améliorent la fiabilité, la flexibilité et la maintenabilité de l'automatisation dans les hiérarchies DOM complexes.
Que contient XPath ?
XPath contient est une fonction au sein d'une expression XPath, utilisée pour rechercher les éléments Web contenant un texte particulier. Nous pouvons extracUtilisez la fonction XPath `contains()` pour rechercher tous les éléments correspondant à la valeur textuelle donnée sur l'ensemble de la page web. `contains` en XPath permet de trouver l'élément contenant une partie du texte.
Exemple – contient du texte
Ici, nous recherchons une ancre contenant du texte comme «SAP M'.
"//h4/a[contains(text(),'SAP M')]"
REMARQUE : Vous pouvez pratiquer l'exercice XPath suivant sur ce https://demo.guru99.com/test/selenium-xpath.html
Si un simple XPath Si notre script de test ne parvient pas à trouver un élément web complexe, nous devons utiliser les fonctions de la bibliothèque XPath 1.0. La combinaison de ces fonctions nous permettra de créer une expression XPath plus précise.
👉 Inscrivez-vous gratuitement en direct Selenium Projet de test
Suivre un frère ou une sœur dans XPath
A Frère ou sœur dans Selenium Pilote Web est une fonction utilisée pour récupérer un élément web frère de l'élément parent. Si l'élément parent est connu, l'élément web peut être facilement trouvé grâce à l'attribut « sibling » de l'expression XPath. Selenium Pilote Web.
Exemple de frère ou sœur dans XPath :
Ici, à partir de l'élément frère de 'a', nous trouvons 'h4'.
"//div[@class='canvas- graph']//a[@href='/accounting.html'][i[@class='icon-usd']]/following-sibling::h4"
AncêtrePour trouver un élément en fonction de son élément parent, nous pouvons utiliser l'attribut ancestor de XPath.
Pour comprendre ces 3 fonctions, prenons un exemple :
Étapes du test :
À noter: Depuis la date de création du tutoriel, la page d'accueil de GuruLa version 99 a été mise à jour ; veuillez utiliser le site de démonstration pour effectuer les tests.
- Allez dans https://demo.guru99.com/test/guru99home/
- Dans la section « Quelques-uns de nos cours les plus populaires », recherchez tous les éléments Web qui sont frères d'un élément Web dont le texte est « SELENIUM ».
- Nous allons rechercher les éléments en utilisant les fonctions XPath text contains, ancestor et sibling.
USING contient du texte et un frère 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();
}
}
}
La sortie sera comme :
Ancêtre XPath dans Selenium
Ancêtre XPath dans Selenium Cette fonction permet de trouver l'ancêtre d'un élément spécifique au niveau indiqué. Le niveau de l'ancêtre à retourner, ou son niveau relatif par rapport à celui de l'élément, peut être spécifié explicitement. Elle renvoie le nombre d'étapes hiérarchiques à partir de l'ancêtre, permettant ainsi de localiser l'ancêtre recherché par l'utilisateur.
Supposons maintenant que nous devions rechercher tous les éléments de la section « Cours populaires » à l’aide de l’ancêtre de l’ancre dont le texte est « SELENIUM ».
Ici, notre requête XPath ressemblera à
"//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();
}
}
}
La sortie ressemblera à-
Utiliser AND et OR
En utilisant AND et OR, vous pouvez inclure 2 conditions dans notre expression XPath.
- Dans le cas d'un ET, les deux conditions doivent être vraies pour que l'élément soit trouvé.
- Dans le cas d'un OU logique, l'une des deux conditions doit être vraie pour que l'élément soit trouvé.
Ici, notre requête XPath ressemblera à ceci :
Xpath=//*[@type='submit' OR @name='btnReset']
Xpath=//input[@type='submit' and @name='btnLogin']
Étapes du test :
- Allez dans https://demo.guru99.com/v1/
- Dans cette section, nous utiliserons le site de démonstration ci-dessus pour rechercher des éléments à l'aide de différentes fonctions XPath.
Vous trouverez un élément utilisant les axes AND et OR, parent, start-with et XPath
ET OU Exemple
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 dans Selenium
Parent dans Selenium Cette méthode permet de récupérer le nœud parent du nœud actuellement sélectionné sur la page web. Elle est très utile lorsqu'on sélectionne un élément et qu'il faut obtenir son élément parent à l'aide de XPath. Cette méthode permet également d'obtenir le parent du parent.
Ici, notre requête XPath ressemblera à ceci :
Xpath=//*[@id='rt-feature']//parent::div
XPath utilisant 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();
}
}
Commence avec
La fonction « Commence par » permet de trouver l'élément dont l'attribut change dynamiquement lors d'une actualisation ou d'autres opérations comme un clic, une soumission, etc.
Ici, notre requête XPath ressemblera à
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();
}
}
Axes XPath
En utilisant les axes XPath, vous pouvez retrouver les éléments dynamiques et très complexes sur une page web. Les axes XPath contiennent plusieurs méthodes pour rechercher un élément. Ici, nous discuterons de quelques méthodes.
Abonnement: Cette fonction renverra l'élément immédiat du composant particulier.
Ici, notre requête XPath ressemblera à
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();
}
}
Précédent: Cette fonction renverra l'élément précédent de l'élément particulier.
Ici, notre requête XPath ressemblera à
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) Descendant: Cette fonction renverra l'élément descendant de l'élément particulier.
Ici, notre requête XPath ressemblera à
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();
}
}










