XPath contém: texto, irmão seguinte e ancestral em Selenium

O que o XPath contém?

XPath contém é uma função dentro da expressão Xpath que é usada para pesquisar os elementos da web que contêm um determinado texto. Podemos extrair todos os elementos que correspondem ao valor de texto fornecido usando a função XPath contains() em toda a página da web. Contém no XPath tem a capacidade de localizar o elemento com texto parcial.

Exemplo – contém texto
Aqui estamos procurando uma âncora .contains texto como 'SAP M'.

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

XPath contém

NOTA: Você pode praticar o seguinte exercício XPath neste https://demo.guru99.com/test/selenium-xpath.html

Se um simples XPath não conseguir encontrar um elemento web complicado para nosso script de teste, precisamos usar as funções da biblioteca XPath 1.0. Com a combinação dessas funções, podemos criar XPath mais específicos.

Seguindo o irmão no XPath

A Irmão em Selenium Driver da Web é uma função usada para buscar um elemento da web que é irmão do elemento pai. Se o elemento pai for conhecido, o elemento da web pode ser facilmente encontrado ou localizado e pode usar o atributo irmão da expressão Xpath no Selenium webdriver.

Exemplo de irmão em XPath:
Aqui, com base no elemento irmão de 'a', encontramos 'h4'

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

Seguindo o irmão no XPath

Antepassado: Para encontrar um elemento com base no elemento pai, podemos usar o atributo ancestral do XPath.

Seguindo o irmão no XPath

Vamos entender essas 3 funções usando um exemplo –

Etapas do teste:

Nota: Desde a data de criação do tutorial a página inicial do Guru99 foi atualizada então use o site de demonstração para executar testes

  1. Acesse https://demo.guru99.com/test/guru99home/
  2. Na seção 'Alguns de nossos cursos mais populares', pesquise todos os Web Elements que são irmãos de um WebElement cujo texto é 'SELENIUM'
  3. Encontraremos o elemento usando o texto XPath que contém a função ancestral e irmã.

Seguindo o irmão no XPath

USING Contém texto e irmão 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();
    }
}

O resultado será como:

USING Contém texto e irmão XPath

Ancestral XPath em Selenium

Ancestral XPath em Selenium é uma função usada para encontrar o ancestral de um membro específico na camada especificada. O nível do ancestral a ser retornado ou o nível do ancestral relativo ao nível do membro pode ser especificado explicitamente. Ele retorna o número de etapas hierárquicas do ancestral, localizando o ancestral especificado que o usuário deseja.

Agora suponha que precisamos pesquisar todos os elementos na seção 'Curso popular' com a ajuda do ancestral da âncora cujo texto é 'SELENIUM'

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

A saída será semelhante a-

Código Completo

Usando E e OU

Usando AND e OR você pode colocar 2 condições em nossa expressão XPath.

  • No caso de AND ambas as 2 condições devem ser verdadeiras, somente ele encontra o elemento.
  • No caso de OR, qualquer uma das 2 condições deve ser verdadeira e somente ele encontra o elemento.

Aqui nossa consulta XPath será como

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

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

Usando E e OU

Etapas do teste:

  1. Acesse https://demo.guru99.com/v1/
  2. Na seção, usaremos o site de demonstração acima para pesquisar elementos com diferentes funções do XPath.

Você encontrará um elemento usando os eixos AND e OR, pai, começa com e XPath

E OU Exemplo

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

}

Pai XPath em Selenium

Pai em Selenium é um método usado para recuperar o nó pai do nó atual selecionado na página da web. É muito útil na situação em que você seleciona um elemento e precisa obter o elemento pai usando Xpath. Este método também é usado para obter o pai do pai.

Aqui nossa consulta XPath será como

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

Pai XPath em Selenium

XPath usando pai

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

	}

}

Começa com

Usando a função Starts-with, você pode encontrar o elemento cujo atributo muda dinamicamente na atualização ou outras operações como clicar, enviar, etc.

Aqui nossa consulta XPath será como

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

Começa com

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

}

Eixos XPath

Ao usar eixos XPath, você pode encontrar elementos dinâmicos e muito complexos em uma página da web. Os eixos XPath contêm vários métodos para encontrar um elemento. Aqui, discutiremos alguns métodos.

seguinte: Esta função retornará o elemento imediato do componente específico.

Aqui nossa consulta XPath será como

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

XPath usando o seguinte
XPath usando o seguinte
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: Esta função retornará o elemento anterior do elemento específico.

Aqui nossa consulta XPath será como

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

XPath usando precedente

XPath usando 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) Descendente: Esta função retornará o elemento descendente do elemento específico.

Aqui nossa consulta XPath será como

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

XPath usando Descendente

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

	}

}

Resumo

  • Existem algumas situações em que o XPath regular não pode ser usado para localizar um elemento. Nessa situação, precisamos de funções diferentes da consulta XPath.
  • Existem algumas funções XPath importantes, como XPath contém, pai, ancestrais, irmão seguinte, etc.
  • Com a ajuda dessas funções, você pode criar expressões XPath complexas. Se precisar entender como usar "contains" especificamente em XPath, a função "contains" no Selenium oferece uma maneira fácil de pesquisar elementos da web com base em correspondências parciais de texto.