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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38534241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:24:13  来源:igfitidea点击:

How to locate a span with a specific text in Selenium? (Using Java)

javaseleniumxpathselenium-webdriver

提问by HosseinK

I'm having trouble locating a span element in Selenium using java.

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

the HTML looks like:

HTML 看起来像:

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

And I've tried the following with no luck:

我尝试了以下但没有运气:

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

and

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

and

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

as well as some other similar attempts. Could you point me to the best method to do this? As it stands I constantly get "Unable to locate element" error in eclipse.

以及其他一些类似的尝试。你能指出我这样做的最佳方法吗?就目前而言,我经常在 Eclipse 中收到“无法定位元素”错误。

采纳答案by Saurabh Gaur

Your all xpathare looks OK, Just some syntacticallyincorrect. you are missing //in your xpath

你的一切xpath看起来都不错,只是一些语法不正确。你//在你的xpath

The correct xpathare as below :-

正确xpath的如下:-

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

Or

或者

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

Or

或者

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

Or you can use cssSelectoras :-

或者您可以cssSelector用作:-

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

Using anyone of the above By locator you can locate element as below :-

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

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

Hope it helps...:)

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

回答by Vicky

For the element below

对于下面的元素

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

The following solution works for me

以下解决方案对我有用

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