XPath 包含:文本、以下兄弟和祖先 Selenium
🚀 智能摘要
XPath 包含、同级和祖先 Selenium 利用结构化关系和文本模式,实现对网页元素的精确识别。这些 XPath 函数增强了复杂 DOM 层级结构中自动化的可靠性、灵活性和可维护性。
XPath 包含什么?
XPath 包含 是 XPath 表达式中的一个函数,用于搜索包含特定文本的网页元素。我们可以举例说明。trac使用 XPath 的 contains() 函数,在整个网页中查找所有与给定文本值匹配的元素。XPath 中的 contains 函数能够查找包含部分文本的元素。
示例 – 包含文本
这里我们搜索一个锚点。包含文本为'SAP M'。
"//h4/a[contains(text(),'SAP M')]"
注意:您可以在此处练习以下 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 的 ancestor 属性。
让我们通过一个例子来理解这三个功能——
测试步骤:
注意: 自教程创建之日起,首页 Guru99 版本已更新,请改用演示站点运行测试。
- 在MyCAD中点击 软件更新 https://demo.guru99.com/test/guru99home/
- 在“我们最受欢迎的一些课程”部分,搜索所有与文本为“SELENIUM”的 WebElement 同级的 WebElement。
- 我们将使用 XPath 的 text contains、ancestor 和 sibling 函数查找元素。
使用包含文本和 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 祖先 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();
}
}
}
输出如下-
使用 AND 和 OR
通过使用 AND 和 OR,您可以在 XPath 表达式中设置 2 个条件。
- 对于 AND 运算符,只有当两个条件都为真时,才能找到该元素。
- 对于 OR 运算,两个条件中必须有一个为真,才能找到该元素。
这里,我们的 XPath 查询将如下所示
Xpath=//*[@type='submit' OR @name='btnReset']
Xpath=//input[@type='submit' and @name='btnLogin']
测试步骤:
- 在MyCAD中点击 软件更新 https://demo.guru99.com/v1/
- 在本节中,我们将使用上面的演示站点,通过 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
使用 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

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










