Hay XPath, After Sibling, Ancestor & Selenium Y / O

Si es simple XPath Al no poder encontrar una característica web compleja para nuestro script de prueba, necesitamos usar las funciones de la biblioteca XPath 1.0. Con la combinación de estas funciones, podemos crear un XPath más específico. Analicemos 3 de tales funciones:

  1. Hermano
  2. Antepasados
  3. Y O
  4. Padre
  5. Empezando con
  6. Ejes XPath

Estudiémoslos en detalle –

Ex. Aquí buscamos un ancla. Incluye texto como ‘SAP M’.

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

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

Hermano en XPath Ejemplo: aquí, sobre la base de un elemento hermano de ‘a’, obtenemos ‘h4’

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

Antepasados: Para obtener un elemento sobre la base del elemento padre, podemos usar el atributo de ancestro 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 use el sitio de demostración en su lugar para ejecutar pruebas.

  1. Ir http://demo.guru99.com/test/guru99home/
  2. En la sección ‘Algunos de los cursos más populares’, busque todos los elementos web hermanos con WebElement cuyo texto sea ‘SELENIUM’
  3. Encontramos que un elemento que usa texto XPath tiene una función de ancestro y hermano.

USE Sibling y XPath son hermanos


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("http://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:

Ahora probablemente tengamos que buscar todos los elementos en la sección ‘Curso común’ con la ayuda del ancestro ancla cuyo texto es ‘SELENIO’

Así será nuestra consulta de xpath

"//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("http://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 aparecerá-

Usando AND y OR

Al usar AND y OR, puede agregar 2 condiciones en nuestra expresión XPath.

Aquí nuestra pregunta XPath se verá así

Xpath=//*[@type="submit" OR @name="btnReset"]
Xpath=//input[@type="submit" and @name="btnLogin"]

Pasos de prueba:

  1. Ir http://demo.guru99.com/v1/
  2. En esta sección, el sitio de demostración anterior se utilizará para buscar un elemento con varias funciones XPath.

Encontrará un elemento utilizando los ejes AND y OR, parent, boot 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();
	}

}

Aquí nuestra pregunta XPath se verá así

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

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

	}

}

Empezando con

Usando la función Comenzar con, puede cambiar dinámicamente el elemento cuyas características cambian al actualizar u otras operaciones como hacer clic, insertar, etc.

Aquí nuestra pregunta XPath se verá así

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

}

Hachas Xpath

Mediante el uso de ejes XPath, puede encontrar los elementos dinámicos y altamente complejos de una página web. Los ejes XPath tienen varios métodos para encontrar un elemento. Aquí discutiremos algunos métodos.

siguiente: Esta función devolverá inmediatamente la característica del componente en particular.

Así es como se verá nuestra consulta XPath

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

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

}

Antes: Esta función devolverá el elemento anterior del elemento dado.

Aquí nuestra pregunta XPath se verá así

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

XPath usando Preceding


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) Extracto: Esta función devolverá el elemento derivado del elemento particular.

Aquí nuestra pregunta XPath se verá así

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

XPath usando Extraer


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

	}

}

Resumen

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *