如何在 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
How to locate a span with a specific text in Selenium? (Using Java)
提问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 xpath
are looks OK, Just some syntacticallyincorrect. you are missing //
in your xpath
你的一切xpath
看起来都不错,只是一些语法不正确。你//
在你的xpath
The correct xpath
are 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 cssSelector
as :-
或者您可以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']")