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

🚀 Resumo Inteligente

XPath contém, irmão e ancestral em Selenium Permitem a identificação precisa de elementos da web usando relações estruturadas e padrões de texto. Essas funções XPath aprimoram a confiabilidade, a flexibilidade e a facilidade de manutenção da automação em hierarquias DOM complexas.

  • Uso contains() Localizar elementos dinâmicos com texto parcial, melhorando a robustez contra variações textuais.
  • Inscreva-se following-sibling e ancestor para percorrer hierarquias de elementos de forma eficiente e extract nós relacionados.
  • Combine funções com operadores lógicos (AND, OR) para uma seleção de elementos refinada e precisa.
  • Utilize os eixos XPath (preceding, descendant) para navegar sistematicamente em árvores DOM complexas.
  • Integre essas expressões em Selenium Scripts para automação de testes web sustentáveis, dinâmicos e resilientes.

XPath contém

O que o XPath contém?

XPath contém é uma função dentro de uma expressão XPath, usada para buscar elementos da web que contenham um texto específico. Podemos exemplificartracA função `contains()` do XPath identifica todos os elementos que correspondem ao valor de texto fornecido em toda a página web. A função `contains()` do XPath permite encontrar elementos 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 Se o sistema não conseguir encontrar um elemento web complexo para o nosso script de teste, precisamos usar as funções da biblioteca XPath 1.0. Combinando essas funções, podemos criar um XPath mais específico.

👉 Inscreva-se gratuitamente para a transmissão ao vivo Selenium Projeto de teste

Seguindo o irmão no XPath

A Irmão em Selenium Driver da Web é uma função usada para buscar um elemento web que seja irmão do elemento pai. Se o elemento pai for conhecido, o elemento web pode ser facilmente encontrado ou localizado, o que pode ser feito usando o atributo `sibling` da expressão XPath. Selenium WebDriver.

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

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

Seguindo o irmão no XPath

AntepassadoPara encontrar um elemento com base no elemento pai, podemos usar o atributo `ancestor` do XPath.

Seguindo o irmão no XPath

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

Etapas do teste:

Observação: Desde a data de criação do tutorial, a página inicial de GuruA versão 99 foi atualizada, portanto, use o site de demonstração para executar os testes.

  1. Acesse https://demo.guru99.com/test/guru99home/
  2. Na seção "Alguns dos nossos cursos mais populares", pesquise todos os elementos da Web que sejam irmãos de um elemento da Web cujo texto seja "SELENIUM".
  3. Encontraremos elementos usando as funções XPath `text contains`, `ancestor` e `sibling`.

Seguindo o irmão no XPath

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

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 elemento específico na camada especificada. O nível do ancestral a ser retornado ou o nível do ancestral em relação ao nível do membro podem ser especificados explicitamente. Ela retorna o número de passos hierárquicos a partir 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 é 'SELÊNIO'.

Aqui nossa consulta xpath será como

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

Automação 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();
        }
    }
}

A saída será semelhante a-

Automação Code

Usando E e OU

Ao usar AND e OR, você pode inserir duas condições em sua expressão XPath.

  • No caso do operador AND, ambas as duas condições devem ser verdadeiras para que o elemento seja encontrado.
  • No caso do operador OR, qualquer uma das duas condições deve ser verdadeira para que o elemento seja encontrado.

Aqui, nossa consulta XPath será assim:

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/
  2. Nesta 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ó selecionado na página da web. É muito útil em situações onde 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á assim:

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 "Começa com", você pode encontrar o elemento cujo atributo muda dinamicamente ao atualizar a página ou em 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();
	}
}

Perguntas Frequentes

Em XPath, /* seleciona todos os elementos de nível raiz de um documento XML ou HTML. Significa "selecione qualquer elemento diretamente abaixo do nó raiz". Por exemplo, em um documento HTML, /* corresponderia a já que é o elemento de nível superior abaixo da raiz.

A função contains() em XPath ajuda a localizar elementos cujo atributo ou texto corresponde parcialmente a um determinado valor. É particularmente útil quando a string exata é imprevisível ou dinâmica. Por exemplo, //div[contains(@class,'menu')] combina com qualquer cuja classe inclui a palavra “menu”.

Para localizar elementos com base em uma correspondência parcial dentro do atributo de classe, use a função contains(). Por exemplo, //button[contains(@class,'submit')] O objetivo é atingir qualquer elemento com um nome de classe que inclua "submit", como "submit-btn" ou "form-submit". É uma maneira flexível de lidar com nomes de classe dinâmicos.

Resuma esta postagem com: