XPath contient : du texte, le frère ou la sœur suivant et l'ancêtre dans Selenium

Que contient XPath ?

XPath contient est une fonction dans l'expression XPath qui est utilisée pour rechercher les éléments Web contenant un texte particulier. Nous pouvons extraire tous les éléments qui correspondent à la valeur de texte donnée à l'aide de la fonction XPath contain() dans toute la page Web. Contient dans XPath a la capacité de trouver l'élément avec un texte partiel.

Exemple – contient du texte
Ici, nous recherchons une ancre contenant du texte comme «SAP M'.

"//h4/a[contains(text(),'SAP M')]"

XPath contient

REMARQUE : Vous pouvez pratiquer l'exercice XPath suivant sur ce https://demo.guru99.com/test/selenium-xpath.html

Si un simple XPath n'est pas en mesure de trouver un élément Web compliqué pour notre script de test, nous devons utiliser les fonctions de la bibliothèque XPath 1.0. Avec la combinaison de ces fonctions, nous pouvons créer des XPath plus spécifiques.

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 qui est un frère de l'élément parent. Si l'élément parent est connu, l'élément Web peut être facilement trouvé ou localisé et peut utiliser l'attribut frère de l'expression XPath dans Selenium Webdriver.

Exemple de frère ou sœur dans XPath :
Ici, sur la base 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"

Suivre un frère ou une sœur dans XPath

Ancêtre: Pour trouver un élément sur la base de l'élément parent, nous pouvons utiliser l'attribut ancêtre de XPath.

Suivre un frère ou une sœur dans XPath

Comprenons ces 3 fonctions à l’aide d’un exemple –

Étapes du test :

Remarque : Depuis la date de création du tutoriel la page d'accueil de Guru99 a été mise à jour donc utilisez plutôt le site de démonstration pour lancer des tests

  1. Cliquez sur https://demo.guru99.com/test/guru99home/
  2. Dans la section 'Quelques-uns de nos cours les plus populaires', recherchez tous les Web Elements qui sont frères d'un WebElement dont le texte est 'SELENIUM'.
  3. Nous trouverons l'élément utilisant le texte XPath contenant la fonction ancêtre et frère.

Suivre un frère ou une sœur dans XPath

USING contient du texte et un frère XPath

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("https://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();
    }
}

La sortie sera comme :

USING contient du texte et un frère XPath

Ancêtre XPath dans Selenium

Ancêtre XPath dans Selenium est une fonction utilisée pour trouver l'ancêtre d'un membre spécifique au niveau de la couche spécifiée. Le niveau d'ancêtre à renvoyer ou le niveau de l'ancêtre par rapport au niveau du membre peut être explicitement spécifié. Il renvoie le nombre d'étapes hiérarchiques de l'ancêtre, localisant l'ancêtre spécifié souhaité par l'utilisateur.

Supposons maintenant que nous devions rechercher tous les éléments dans la section « Cours populaire » à 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 complet

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("https://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();
    }
}

La sortie ressemblera à-

Code complet

Utiliser AND et OR

En utilisant AND et OR, vous pouvez mettre 2 conditions dans notre expression XPath.

  • Dans le cas de AND, les deux conditions doivent être vraies, alors seulement il trouve l'élément.
  • En cas de OU, l'une des 2 conditions doit être vraie, alors seulement il trouve l'élément.

Ici, notre requête XPath ressemblera à

Xpath=//*[@type='submit' OR @name='btnReset']

Xpath=//input[@type='submit' and @name='btnLogin']

Utiliser AND et OR

Étapes du test :

  1. Cliquez sur https://demo.guru99.com/v1/
  2. Dans la section, nous utiliserons le site de démonstration ci-dessus pour rechercher des éléments avec différentes fonctions de 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 est une méthode utilisée pour récupérer le nœud parent du nœud actuel sélectionné dans la page Web. C'est très utile dans le cas où vous sélectionnez un élément et devez obtenir l'élément parent à l'aide de XPath. Cette méthode est également utilisée pour obtenir le parent du parent.

Ici, notre requête XPath ressemblera à

Xpath=//*[@id='rt-feature']//parent::div

Parent XPath dans Selenium

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

En utilisant la fonction Commence par, vous pouvez trouver l'élément dont l'attribut change dynamiquement lors de l'actualisation ou d'autres opérations comme cliquer, soumettre, etc.

Ici, notre requête XPath ressemblera à

Xpath=//label[starts-with(@id,'message')]

Commence avec

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

XPath en utilisant le suivi
XPath utilisant ce qui suit
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

XPath utilisant le précédent

XPath utilisant le précédent
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

XPath utilisant Descendant

XPath utilisant Descendant
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();

	}

}

Résumé

  • Il existe certaines situations dans lesquelles XPath standard ne peut pas être utilisé pour rechercher un élément. Dans une telle situation, nous avons besoin de fonctions différentes de la requête XPath.
  • Il existe des fonctions XPath importantes telles que XPath contient, parent, ancêtres, frère suivant, etc.
  • À l'aide de ces fonctions, vous pouvez créer des expressions XPath complexes.