XPath contiene: texto, siguiente hermano y antepasado en Selenium

🚀 Resumen inteligente

XPath Contiene, Hermano y Ancestro en Selenium Permiten la identificación precisa de elementos web mediante relaciones estructuradas y patrones de texto. Estas funciones XPath mejoran la fiabilidad, la flexibilidad y la mantenibilidad de la automatización en jerarquías DOM complejas.

  • Usar contains() para localizar elementos dinámicos con texto parcial, mejorando la robustez frente a variaciones de texto.
  • Aplicar following-sibling y ancestor para recorrer jerarquías de elementos de manera eficiente y extract nodos relacionados.
  • Combine funciones con operadores lógicos (AND, OR) para una selección de elementos precisa y refinada.
  • Utilice los ejes XPath (precedente, descendiente) para navegar sistemáticamente por árboles DOM complejos.
  • Integra estas expresiones en Selenium Scripts para la automatización de pruebas web mantenibles, dinámicas y resilientes.

XPath contiene

¿Qué contiene XPath?

XPath contiene es una función dentro de una expresión XPath, que se utiliza para buscar elementos web que contengan un texto en particular. Podemos extracEncuentre todos los elementos que coincidan con el valor de texto dado utilizando la función contains() de XPath en toda la página web. La función contains 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 de XPath en este https://demo.guru99.com/test/selenium-xpath.html

si un sencillo XPath Al no poder encontrar un elemento web complejo para nuestro script de prueba, necesitamos usar las funciones de la biblioteca XPath 1.0. Combinando estas funciones, podemos crear un XPath más específico.

👉 Inscríbete gratis en directo Selenium Proyecto de prueba

Seguimiento de hermanos en XPath

A hermano en Selenium controlador web es una función utilizada para obtener un elemento web que es hermano del elemento padre. Si se conoce el elemento padre, entonces el elemento web se puede encontrar o localizar fácilmente, lo cual se puede hacer utilizando el atributo sibling de la expresión XPath en Selenium Controlador web.

Ejemplo de hermano en XPath:
Aquí, basándonos en el 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

AntepasadoPara encontrar un elemento basándonos en su elemento padre, podemos usar el atributo ancestor de XPath.

Seguimiento de hermanos en XPath

Vamos a entender estas 3 funciones con un ejemplo:

Pasos de prueba:

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

  1. Vaya al 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 elemento web cuyo texto sea 'SELENIUM'.
  3. Encontraremos elementos utilizando las funciones XPath text contains, ancestor y sibling.

Seguimiento de hermanos en XPath

USING Contiene texto y hermano 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 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 elemento específico en la capa indicada. Se puede especificar explícitamente el nivel del ancestro que se devolverá o su nivel relativo al del elemento. Devuelve el número de pasos jerárquicos desde el ancestro, localizando así el ancestro deseado por el usuario.

Supongamos ahora que necesitamos buscar todos los elementos en la sección 'Curso popular' con la ayuda del ancestro 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"

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

Paquete COMPLETE Code

Usando Y y O

Al usar AND y OR, puedes incluir dos condiciones en nuestra expresión XPath.

  • En el caso de AND, ambas condiciones deben ser verdaderas, solo entonces encontrará el elemento.
  • En el caso de OR, cualquiera de las dos condiciones debe ser verdadera, solo entonces encontrará 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 al https://demo.guru99.com/
  2. En esta 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 que se utiliza para recuperar el nodo padre del nodo seleccionado en la página web. Resulta muy útil cuando se selecciona un elemento y se necesita obtener su elemento padre mediante XPath. Este método también se utiliza para obtener el padre del elemento padre.

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

Utilizando la función "Empieza con", puedes encontrar el elemento cuyo atributo cambia dinámicamente al actualizar la página o al realizar 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();
	}
}

Preguntas Frecuentes

En XPath, /* selecciona todos los elementos de nivel raíz de un documento XML o HTML. Significa "seleccionar cualquier elemento directamente debajo del nodo raíz". Por ejemplo, en un documento HTML, /* coincidiría con ya que es el elemento de nivel superior debajo de la raíz.

La función contains() en XPath ayuda a localizar elementos cuyo atributo o texto coincide parcialmente con un valor dado. Es especialmente útil cuando la cadena exacta es impredecible o dinámica. Por ejemplo, //div[contains(@class,'menu')] coincide con cualquiera cuya clase incluye la palabra “menú”.

Para localizar elementos basándose en una coincidencia parcial dentro de su atributo de clase, utilice la función contains(). Por ejemplo, //button[contains(@class,'submit')] Se dirige a cualquier elemento cuyo nombre de clase incluya "submit", como "submit-btn" o "form-submit". Es una forma flexible de gestionar nombres de clase dinámicos.

Resumir este post con: