如何使用 selenium 和 css 获取属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7201337/
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 get attribute value using selenium and css
提问by Sunny
I have the following HTML code:
我有以下 HTML 代码:
<a href="/search/?p=2&q=move&mt=1"> 2 </a>
I would like to get what is contained in href, ie, I was looking for a command which would give me "/search/?p=2&q=move&mt=1" value for href.
我想获得 href 中包含的内容,即,我正在寻找一个命令,该命令将为我提供“/search/?p=2&q=move&mt=1”值的 href。
Could someone please help me with the respective command and css locator in selenium, for the above query?
对于上述查询,有人可以帮助我使用 selenium 中的相应命令和 css 定位器吗?
if I have something like:
如果我有类似的东西:
<a href="/search/?p=2&q=move&mt=1"> 2 </a>
<a href="/search/?p=2&q=move&mt=2"> 3 </a>
Out of these two if I was to get the attribute value for href whose text conatins '2', then how would my css locator synatx look like?
在这两个中,如果我要获取文本包含“2”的 href 的属性值,那么我的 css 定位器 synatx 会是什么样子?
采纳答案by BoltClock
If your HTML consists solely of that one <a>
tag, then this should do it:
如果您的 HTML 仅包含该<a>
标签,则应该这样做:
String href = selenium.getAttribute("css=a@href");
You use the DefaultSelenium#getAttribute()
methodand pass in a CSS locator, an @
symbol, and the name of the attribute you want to fetch. In this case, you select the a
and get its @href
.
您使用该DefaultSelenium#getAttribute()
方法并传入一个 CSS 定位器、一个@
符号和要获取的属性的名称。在这种情况下,您选择a
并获取其@href
。
In response to your comment/edit:
回应您的评论/编辑:
The part after
@
tells Selenium that that part is the name of the attribute.You should place
:contains('2')
before@href
because it's part of the locator, not the attribute. So, like this:selenium.getAttribute("css=a:contains('2')@href");
后面的部分
@
告诉 Selenium 该部分是属性的名称。您应该放在
:contains('2')
之前,@href
因为它是定位器的一部分,而不是属性。所以,像这样:selenium.getAttribute("css=a:contains('2')@href");
回答by Vinay
Changing css=a@href to href should do the trick. Let me if this did not work.
将 css=a@href 更改为 href 应该可以解决问题。如果这不起作用,请让我。
List<WebElement> ele = driver.findElements(By.className("c"));
for(WebElement e : ele)
{
String doctorname = e.getText();
String linkValue = e.getAttribute("href");
}