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.
ยฟQuรฉ contiene XPath?
XPath contiene `contains()` es una funciรณn dentro de una expresiรณn XPath que se utiliza para buscar los elementos web que contienen un texto especรญfico. Podemos extraer todos los elementos que coincidan con el valor de texto dado utilizando la funciรณn `contains()` de XPath en toda la pรกgina web. `contains()` en XPath permite encontrar elementos con texto parcial.
Ejemplo: contiene texto
Aquรญ estamos buscando un ancla que contiene texto como 'SAP METRO'.
"//h4/a[contains(text(),'SAP M')]"
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"
AntepasadoPara encontrar un elemento basรกndonos en su elemento padre, podemos usar el atributo ancestor de XPath.
Vamos a entender estas 3 funciones con un ejemplo:
Pasos de prueba:
Nota: Desde la fecha de creaciรณn de este tutorial, la pรกgina principal de Guru99 se ha actualizado, por lo que se recomienda utilizar el sitio de demostraciรณn para realizar las pruebas.
- Vaya a https://demo.guru99.com/test/guru99home/
- 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'.
- Encontraremos elementos utilizando las funciones XPath text contains, ancestor y sibling.
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:
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"
Cรณdigo Completo
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รญ-
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']
Pasos de prueba:
- Vaya a https://demo.guru99.com/v1/
- 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 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')]
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

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










