XPath 包含:文本、以下兄弟和祖先 Selenium

XPath 包含什么?

XPath 包含 是 Xpath 表达式中的一个函数,用于搜索包含特定文本的 Web 元素。我们可以使用 XPath contains() 函数在整个网页中提取与给定文本值匹配的所有元素。XPath 中的 Contains 能够查找具有部分文本的元素。

示例 – 包含文本
这里我们搜索一个锚点。包含文本为'SAP M'。

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

XPath 包含

注意:您可以在此处练习以下 XPath 练习 https://demo.guru99.com/test/selenium-xpath.html

如果一个简单的 XPath的 无法为我们的测试脚本找到复杂的 Web 元素,我们需要使用 XPath 1.0 库中的函数。通过组合这些函数,我们可以创建更具体的 XPath。

在 XPath 中关注兄弟

A 兄弟姐妹 Selenium 网络驱动程序 是用于获取父元素的兄弟 Web 元素的函数。如果父元素已知,则可以轻松找到或定位 Web 元素,这可以使用 selenium webdriver 中 Xpath 表达式的兄弟属性。

XPath 中的兄弟示例:
这里我们根据 'a' 的兄弟元素找到 'h4'

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

在 XPath 中关注兄弟

祖先:要根据父元素查找元素,我们可以使用 XPath 的祖先属性。

在 XPath 中关注兄弟

让我们通过一个例子来理解这三个函数——

测试步骤:

请注意: 自本教程创建之日起,Guru99 的主页已更新,因此请使用演示网站来运行测试

  1. 在MyCAD中点击 软件更新 https://demo.guru99.com/test/guru99home/
  2. 在“我们最受欢迎的一些课程”部分中,搜索所有与文本为“SELENIUM”的 WebElement 同级的 Web Element
  3. 我们将使用 XPath 文本包含、祖先和兄弟函数来查找元素。

在 XPath 中关注兄弟

使用包含文本和 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();
    }
}

输出将会像这样:

使用包含文本和 XPath 兄弟

XPath 祖先 Selenium

XPath 祖先 Selenium 是用于查找特定成员在指定层级的祖先的函数。可以明确指定要返回的祖先层级或祖先层级相对于成员层的层级。它从祖先返回层级步骤数,定位用户想要的指定祖先。

现在假设我们需要在文本为“SELENIUM”的锚点祖先的帮助下搜索“热门课程”部分中的所有元素

这里我们的 xpath 查询将会是这样的

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

完整的代码

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

输出如下-

完整的代码

使用 AND 和 OR

通过使用 AND 和 OR,您可以在我们的 XPath 表达式中放置 2 个条件。

  • 如果是 AND 则两个条件都必须为真,这样才会找到元素。
  • 如果是 OR 的话,只要两个条件中的一个为真,就能找到该元素。

这里我们的 XPath 查询将类似于

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

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

使用 AND 和 OR

测试步骤:

  1. 在MyCAD中点击 软件更新 https://demo.guru99.com/v1/
  2. 在本节中,将使用上述演示站点使用 XPath 的不同功能来搜索元素。

您将使用 AND 和 OR、父级、以...开头以及 XPath 轴查找元素

AND OR 示例

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 父级 Selenium

父母在 Selenium 是用于检索网页中当前所选节点的父节点的方法。当您选择一个元素并需要使用 Xpath 获取父元素时,该方法非常有用。此方法还用于获取父元素的父元素。

这里我们的 XPath 查询将类似于

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

XPath 父级 Selenium

使用 Parent 的 XPath

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

	}

}

以。。开始

使用 Starts-with 函数,您可以找到在刷新或其他操作(例如单击、提交等)时属性会动态变化的元素。

这里我们的 XPath 查询将类似于

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

}

Xpath 轴

通过使用 XPath 轴,您可以找到网页上的动态且非常复杂的元素。XPath 轴包含几种查找元素的方法。这里将讨论几种方法。

以下:此函数将返回特定组件的直接元素。

这里我们的 XPath 查询将类似于

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

使用 Following 的 XPath
XPath 使用以下
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();
	}

}

前: 此函数将返回特定元素的前一个元素。

这里我们的 XPath 查询将类似于

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

使用前置的 XPath

使用前置的 XPath
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) 后裔: 此函数将返回特定元素的后代元素。

这里我们的 XPath 查询将类似于

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

使用后代的 XPath

使用后代的 XPath
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();

	}

}

总结

  • 在某些情况下,常规 XPath 无法用于查找元素。在这种情况下,我们需要与 xpath 查询不同的功能。
  • 有一些重要的 XPath 函数,如 XPath 包含、父母、祖先、跟随兄弟等。
  • 借助这些函数,您可以创建复杂的 XPath 表达式。