XPath contiene: testo, fratello e antenato seguenti in Selenium

๐Ÿš€ Riepilogo intelligente

XPath contiene, fratello e antenato in Selenium Consentono l'identificazione precisa degli elementi web utilizzando relazioni strutturate e pattern testuali. Queste funzioni XPath migliorano l'affidabilitร , la flessibilitร  e la manutenibilitร  dell'automazione in gerarchie DOM complesse.

  • Usa il contains() per individuare elementi dinamici con testo parziale, migliorando la robustezza rispetto alle variazioni del testo.
  • APPLICA following-sibling and ancestor attraversare le gerarchie degli elementi in modo efficiente ed efficientetracnodi correlati.
  • Combina le funzioni con gli operatori logici (AND, OR) per un targeting degli elementi preciso e preciso.
  • Sfrutta gli assi XPath (precedente, discendente) per navigare in modo sistematico negli alberi DOM complessi.
  • Integra queste espressioni in Selenium script per l'automazione dei test web manutenibile, dinamica e resiliente.

XPath contiene

Che cosa contiene XPath?

XPath contiene รจ una funzione all'interno di un'espressione XPath, che viene utilizzata per cercare gli elementi web che contengono un testo particolare. Possiamo esplicaretracTutti gli elementi che corrispondono al valore di testo specificato vengono recuperati utilizzando la funzione `contains()` di XPath all'interno della pagina web. La funzione `contains()` in XPath รจ in grado di trovare l'elemento con testo parziale.

Esempio: contiene testo

Qui stiamo cercando un'ancora che contenga testo come 'SAP M'.

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

XPath contiene

NOTA: puoi esercitarti con il seguente esercizio XPath su questo https://demo.guru99.com/test/selenium-xpath.html

Se un semplice XPath non riesce a trovare un elemento web complesso per il nostro script di test, dobbiamo utilizzare le funzioni della libreria XPath 1.0. Combinando queste funzioni, possiamo creare un XPath piรน specifico.

๐Ÿ‘‰ Iscriviti gratuitamente in diretta Selenium Progetto di prova

Seguire il fratello in XPath

A Fratello dentro Selenium Webdriver รจ una funzione utilizzata per recuperare un elemento web che รจ fratello dell'elemento padre. Se l'elemento padre รจ noto, l'elemento web puรฒ essere facilmente trovato o localizzato, il che puรฒ utilizzare l'attributo sibling dell'espressione XPath in Selenium WebDriver.

Fratello nell'esempio XPath:
Qui, sulla base dell'elemento fratello di 'a' troviamo 'h4'

"//div[@class='canvas- graph']//a[@href='/accounting.html'][i[@class='icon-usd']]/following-sibling::h4"

Seguire il fratello in XPath

Antenato: Per trovare un elemento sulla base dell'elemento padre, possiamo usare l'attributo ancestor di XPath.

Seguire il fratello in XPath

Cerchiamo di capire queste 3 funzioni usando un esempio:

Passaggi del test:

Nota: Dalla data di creazione del tutorial, la homepage di GuruLa versione 99 รจ stata aggiornata, quindi per eseguire i test utilizzare il sito demo.

  1. Vai su https://demo.guru99.com/test/guru99home/
  2. Nella sezione "Alcuni dei nostri corsi piรน popolari", cerca tutti gli elementi Web che sono fratelli di un WebElement il cui testo รจ "SELENIUM"
  3. Troveremo gli elementi utilizzando le funzioni XPath text contains, ancestor e sibling.

Seguire il fratello in XPath

UTILIZZO Contiene testo e fratello 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();
        }
    }
}

L'output sarร  come:

UTILIZZO Contiene testo e fratello XPath

Antenato XPath in Selenium

Antenato XPath in Selenium รจ una funzione utilizzata per trovare l'antenato di un elemento specifico al livello specificato. Il livello dell'antenato da restituire o il livello dell'antenato rispetto al livello del membro puรฒ essere specificato esplicitamente. Restituisce il numero di passaggi gerarchici dall'antenato, individuando l'antenato specificato desiderato dall'utente.

Ora, supponiamo di dover cercare tutti gli elementi nella sezione "Corso popolare" con l'aiuto dell'antenato dell'ancora il cui testo รจ "SELENIUM"

Qui la nostra query xpath sarร  come

"//div[.//a[text()='SELENIUM']]/ancestor::div[@class='rt-grid-2 rt-omega']/following-sibling::div"

Completato 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();
        }
    }
}

L'output sarร  simile a:

Completato Code

Utilizzando AND e OR

Utilizzando AND e OR, รจ possibile inserire 2 condizioni nella nostra espressione XPath.

  • Nel caso di AND, entrambe le 2 condizioni devono essere vere, solo allora viene trovato l'elemento.
  • Nel caso di OR, una qualsiasi delle 2 condizioni deve essere vera, solo allora viene trovato l'elemento.

Qui, la nostra query XPath sarร  simile a

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

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

Utilizzando AND e OR

Passaggi del test:

  1. Vai su https://demo.guru99.com/v1/
  2. In questa sezione utilizzeremo il sito demo sopra indicato per cercare elementi con diverse funzioni di XPath.

Troverai un elemento che utilizza gli assi AND e OR, genitore, inizia con e XPath

AND OR Esempio

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 Genitore in Selenium

Genitore dentro Selenium รจ un metodo utilizzato per recuperare il nodo padre del nodo correntemente selezionato nella pagina web. รˆ molto utile nelle situazioni in cui si seleziona un elemento e si ha bisogno di ottenere l'elemento padre tramite XPath. Questo metodo viene utilizzato anche per ottenere il padre del nodo padre.

Qui, la nostra query XPath sarร  simile a

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

XPath Genitore in Selenium

XPath utilizzando 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();
	}
}

Inizia con

Utilizzando la funzione Starts-with, puoi trovare l'elemento il cui attributo cambia dinamicamente durante l'aggiornamento o altre operazioni come clic, invio, ecc.

Qui la nostra query XPath sarร  come

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

Inizia con

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();
	}
}

Assi Xpath

Utilizzando gli assi XPath, puoi trovare gli elementi dinamici e molto complessi su una pagina web. Gli assi XPath contengono diversi metodi per trovare un elemento. Qui, discuteremo alcuni metodi.

i seguenti: Questa funzione restituirร  l'elemento immediato del particolare componente.

Qui la nostra query XPath sarร  come

Xpath=//*[@type='text']//following::input

XPath utilizzando Following
XPath utilizzando quanto segue
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();
	}
}

Precedente: Questa funzione restituirร  l'elemento precedente del particolare elemento.

Qui la nostra query XPath sarร  come

Xpath= //*[@type='submit']//preceding::input

XPath utilizzando Precedente

XPath utilizzando Precedente
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) Discendente: Questa funzione restituirร  l'elemento discendente del particolare elemento.

Qui la nostra query XPath sarร  come

Xpath= //*[@id='rt-feature']//descendant::a

XPath utilizzando il discendente

XPath utilizzando il discendente
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();
	}
}

DOMANDE FREQUENTI

In XPath, /* seleziona tutti gli elementi di livello radice di un documento XML o HTML. Significa "seleziona qualsiasi elemento direttamente sotto il nodo radice". Ad esempio, in un documento HTML, /* corrisponderebbe a poichรฉ รจ l'elemento di livello superiore sotto la radice.

La funzione contains() in XPath aiuta a individuare gli elementi il โ€‹โ€‹cui attributo o testo corrisponde parzialmente a un dato valore. รˆ particolarmente utile quando la stringa esatta รจ imprevedibile o dinamica. Ad esempio, //div[contains(@class,'menu')] corrisponde a qualsiasi la cui classe include la parola โ€œmenuโ€.

Per individuare gli elementi in base a una corrispondenza parziale all'interno del loro attributo di classe, utilizzare la funzione contains(). Ad esempio, //button[contains(@class,'submit')] prende di mira qualsiasi classe con un nome che include "submit", come "submit-btn" o "form-submit". รˆ un modo flessibile per gestire i nomi di classe dinamici.

Riassumi questo post con: