如何在 Selenium 中定位具有特定文本的跨度? (使用Java)

问题描述 投票:0回答:3

我在使用 java 查找 Selenium 中的 span 元素时遇到问题。

HTML 看起来像:

<div class="settings-padding">
<span>Settings</span>
</div>

我尝试了以下方法,但没有成功:

By.xpath("span[.='Settings']")

By.xpath("span[text()='Settings']")

By.cssSelector("div[class='settings-padding']"))

以及其他一些类似的尝试。你能指出我最好的方法吗?就目前情况而言,我在 Eclipse 中不断收到“无法定位元素”错误。

java selenium xpath selenium-webdriver
3个回答
34
投票

您的所有

xpath
看起来都不错,只是有些语法不正确。你的
//
 中缺少 
xpath

正确的

xpath
如下:-

By by = By.xpath("//span[.='Settings']")

或者

By by = By.xpath("//span[text()='Settings']")

或者

By by = By.xpath("//div[@class='settings-padding']/span"))

或者您可以将

cssSelector
用作 :-

By by = By.cssSelector("div.settings-padding > span"))

使用上述任何一种通过定位器,您可以找到如下元素:-

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement el = wait.until(presenceOfElementLocated(by));

希望有帮助...:)


2
投票

对于下面的元素

<span class="test-button__text">
    Test Text
</span>

以下解决方案对我有用

driver.find_element_by_xpath("//span[contains(@class, 'test-button__text') and text()='Test Text']")

0
投票

这在 C# 中对我有用(假定 Java 等效,但未测试):

C#

By by = By.CssSelector("span[class='settings-padding']"))

Java

By by = By.cssSelector("span[class='settings-padding']"))
© www.soinside.com 2019 - 2024. All rights reserved.