XPath contiene: texto, siguiente hermano y antepasado en Selenium

¿Qué contiene XPath?

XPath contiene es una función dentro de la expresión XPath que se utiliza para buscar elementos web que contienen un texto en particular. Podemos extraer todos los elementos que coinciden con el valor de texto dado usando la función XPath contains() en toda la página web. Contiene en XPath tiene la capacidad de encontrar el elemento con texto parcial.

Ejemplo: contiene texto
Aquí estamos buscando un ancla que contiene texto como 'SAP METRO'.

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

XPath contiene

NOTA: Puedes practicar el siguiente ejercicio XPath en este https://demo.guru99.com/test/selenium-xpath.html

si un sencillo XPath No podemos encontrar un elemento web complicado para nuestro script de prueba, necesitamos usar las funciones de la biblioteca XPath 1.0. Con la combinación de estas funciones, podemos crear XPath más específicos.

Seguimiento de hermanos en XPath

A hermano en Selenium controlador web es una función que se utiliza para obtener un elemento web que es hermano del elemento padre. Si se conoce el elemento padre, se puede encontrar o ubicar fácilmente el elemento web mediante el atributo hermano de la expresión XPath en Selenium WebDriver.

Ejemplo de hermano en XPath:
Aquí, sobre la base del elemento hermano de 'a', encontramos 'h4'

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

Seguimiento de hermanos en XPath

Antepasado: Para encontrar un elemento basándose en el elemento principal, podemos utilizar el atributo ancestro de XPath.

Seguimiento de hermanos en XPath

Entendamos estas 3 funciones usando un ejemplo:

Pasos de prueba:

Nota: Desde la fecha de creación del tutorial, la página de inicio de Guru99 se ha actualizado, así que utilice el sitio de demostración para ejecutar pruebas.

  1. Vaya a https://demo.guru99.com/test/guru99home/
  2. En la sección "Algunos de nuestros cursos más populares", busque todos los elementos web que sean hermanos de un WebElement cuyo texto sea "SELENIUM".
  3. Encontraremos que el elemento que utiliza texto XPath contiene funciones de antepasado y hermano.

Seguimiento de hermanos en XPath

USING Contiene texto y hermano 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 salida será como:

USING Contiene texto y hermano XPath

Ancestro XPath en Selenium

Ancestro XPath en Selenium es una función que se utiliza para encontrar el ancestro de un miembro específico en la capa especificada. El nivel del ancestro que se devolverá o el nivel del ancestro en relación con el nivel del miembro se pueden especificar explícitamente. Devuelve el número de pasos jerárquicos a partir del ancestro, y ubica el ancestro especificado que el usuario desea.

Ahora supongamos que necesitamos buscar todos los elementos en la sección "Curso popular" con la ayuda del antepasado del ancla cuyo texto es "SELENIUM".

Aquí nuestra consulta xpath será como

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

Código Completo

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 salida se verá así-

Código Completo

Usando Y y O

Al usar AND y OR puedes poner 2 condiciones en nuestra expresión XPath.

  • En el caso de AND, ambas 2 condiciones deben ser verdaderas, entonces solo encuentra el elemento.
  • En el caso de OR, cualquiera de las 2 condiciones debe ser verdadera, entonces solo encuentra el elemento.

Aquí nuestra consulta XPath será como

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

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

Usando Y y O

Pasos de prueba:

  1. Vaya a https://demo.guru99.com/v1/
  2. En la sección, utilizaremos el sitio de demostración anterior para buscar elementos con diferentes funciones de XPath.

Encontrará un elemento que utiliza los ejes AND y OR, principal, comienza con y XPath.

Y O Ejemplo

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 padre en Selenium

Padre en Selenium es un método utilizado para recuperar el nodo principal del nodo actual seleccionado en la página web. Es muy útil en la situación en la que selecciona un elemento y necesita obtener el elemento principal usando XPath. Este método también se utiliza para obtener el padre de los padres.

Aquí nuestra consulta XPath será como

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

XPath padre en Selenium

XPath usando padre

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

	}

}

Comienza con

Usando la función Comienza con, puede encontrar el elemento cuyo atributo cambia dinámicamente al actualizar u otras operaciones como hacer clic, enviar, etc.

Aquí nuestra consulta XPath será como

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

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

}

Ejes XPath

Al utilizar los ejes XPath, puede encontrar elementos dinámicos y muy complejos en una página web. Los ejes XPath contienen varios métodos para encontrar un elemento. Aquí, analizaremos algunos métodos.

siguiendo: Esta función devolverá el elemento inmediato del componente particular.

Aquí nuestra consulta XPath será como

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

XPath usando lo siguiente
XPath usando lo siguiente
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();
	}

}

Anterior: Esta función devolverá el elemento anterior del elemento particular.

Aquí nuestra consulta XPath será como

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

XPath usando el precedente

XPath usando el 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) Descendiente: Esta función devolverá el elemento descendiente del elemento particular.

Aquí nuestra consulta XPath será como

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

XPath usando descendiente

XPath usando descendiente
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();

	}

}

Resum

  • Hay algunas situaciones en las que no se puede utilizar XPath normal para encontrar un elemento. En tal situación, necesitamos funciones diferentes de la consulta xpath.
  • Hay algunas funciones XPath importantes como XPath contiene, padre, ancestros, siguiente hermano, etc.
  • Con la ayuda de estas funciones, puede crear expresiones XPath complejas.