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

🚀 智能摘要

XPath 包含、同级和祖先 Selenium 利用结构化关系和文本模式,实现对网页元素的精确识别。这些 XPath 函数增强了复杂 DOM 层级结构中自动化的可靠性、灵活性和可维护性。

  • 绝大部分储备使用 contains() 定位包含部分文本的动态元素,提高对文本变化的鲁棒性。
  • 在断裂前, following-siblingancestor 高效地遍历元素层级结构并例如tract 个相关节点。
  • 将函数与逻辑运算符(AND、OR)结合使用,以实现更精细、更精确的元素定位。
  • 利用 XPath 轴(前置、后置)系统地导航复杂的 DOM 树。
  • 将这些表达式整合起来 Selenium 用于可维护、动态和弹性的 Web 测试自动化的脚本。

XPath 包含

XPath 包含什么?

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

示例 – 包含文本

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

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

XPath 包含

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

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

👉 免费报名参加直播 Selenium 测试项目

在 XPath 中关注兄弟

A 兄弟姐妹 Selenium 网络驱动程序 这是一个用于获取与父元素同级的网页元素的函数。如果已知父元素,则可以轻松找到或定位目标网页元素,这可以通过使用 XPath 表达式的 sibling 属性来实现。 Selenium WebDriver。

XPath 中的兄弟示例:
这里,我们根据“a”的同级元素找到了“h4”。

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

在 XPath 中关注兄弟

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

在 XPath 中关注兄弟

让我们通过一个例子来理解这三个功能——

测试步骤:

注意: 自教程创建之日起,首页 Guru99 版本已更新,请改用演示站点运行测试。

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

在 XPath 中关注兄弟

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

输出将会像这样:

使用包含文本和 XPath 兄弟

XPath 祖先 Selenium

XPath 祖先 Selenium 该函数用于查找指定层级中特定元素的祖先元素。可以显式指定要返回的祖先元素层级,或者祖先元素相对于当前成员层的层级。它返回从目标祖先元素开始的层级步骤数,从而定位到用户指定的祖先元素。

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

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

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

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

输出如下-

完成: Code

使用 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 中,/* 选择 XML 或 HTML 文档的所有根级元素。它的意思是“选择根节点下的所有元素”。例如,在 HTML 文档中,/* 将匹配 <html> 标签。因为它是根元素下的顶级元素。

XPath 中的 contains() 函数可以帮助查找属性或文本部分匹配给定值的元素。当确切的字符串不可预测或动态变化时,它尤其有用。例如: //div[contains(@class,'menu')] 匹配任何其类别包含单词“menu”。

要根据类属性中的部分匹配来定位元素,请使用 contains() 函数。例如: //button[contains(@class,'submit')] 它会针对类名中包含“submit”的任何元素,例如“submit-btn”或“form-submit”。这是一种处理动态类名的灵活方法。

总结一下这篇文章: