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

Hos*_*inK 7 java selenium xpath selenium-webdriver

我在使用java在Selenium中找到span元素时遇到了麻烦.

HTML看起来像:

<div class="settings-padding">
<span>Settings</span>
</div>
Run Code Online (Sandbox Code Playgroud)

而且我尝试了下面没有运气:

By.xpath("span[.='Settings']")
Run Code Online (Sandbox Code Playgroud)

By.xpath("span[text()='Settings']")
Run Code Online (Sandbox Code Playgroud)

By.cssSelector("div[class='settings-padding']"))
Run Code Online (Sandbox Code Playgroud)

以及其他一些类似的尝试.你能指点我做最好的方法吗?在它看来我经常在eclipse中得到"无法找到元素"错误.

Sau*_*aur 15

你的一切xpath看起来还不错,只是在语法上不正确.你错过//xpath

正确xpath如下: -

By by = By.xpath("//span[.='Settings']")
Run Code Online (Sandbox Code Playgroud)

要么

By by = By.xpath("//span[text()='Settings']")
Run Code Online (Sandbox Code Playgroud)

要么

By by = By.xpath("//div[@class='settings-padding']/span"))
Run Code Online (Sandbox Code Playgroud)

或者您可以使用cssSelector: -

By by = By.cssSelector("div.settings-padding > span"))
Run Code Online (Sandbox Code Playgroud)

使用上述By定位器中的任何一个,您可以找到如下元素: -

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement el = wait.until(presenceOfElementLocated(by));
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你...:)