Java 如何使用 css 选择器提取属性值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1972428/
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-13 01:56:55  来源:igfitidea点击:

How to extract attribute values using css selectors?

javaseleniumcss-selectors

提问by John

I want to select the values of attributes of an element. e.g If I have an input element

我想选择元素的属性值。例如,如果我有一个输入元素

<input type="text" name=myInput value="100">

I can locate it using input[name='myInput'], but how do I get the value of it using a css selector?

我可以使用 定位它input[name='myInput'],但是如何使用 css 选择器获取它的值?

BTW, I am trying to do this in Selenium using css selectors

顺便说一句,我正在尝试使用 css 选择器在 Selenium 中执行此操作

采纳答案by slebetman

If in Perl using WWW::Selenium then it's simply:

如果在 Perl 中使用 WWW::Selenium 那么它只是:

my $val = $selenium->get_value("css=input[name='myInput']");

If using another language then the Selenium library should support a get_value function/method.

如果使用另一种语言,则 Selenium 库应该支持 get_value 函数/方法。

回答by Joe

You might want to explain what you're trying to do with the value. For instance, I have the following CSS to display the text of the links in the '#content' element in my print style sheet:

您可能想解释您试图用该值做什么。例如,我使用以下 CSS 来显示打印样式表中“#content”元素中链接的文本:

#content a:link:after, #content  a:visited:after {
    content: " (" attr(href) ") ";
    font-size: 90%;
}

#content a[href^="/"]:after {
    content: " (http://example.com" attr(href) ") ";
}

回答by Macha

Your favorite JavaScript library should have some way to do this:

你最喜欢的 JavaScript 库应该有办法做到这一点:

jQuery

jQuery

$("input[name=myname]").val()

Prototype's method for CSS seloctors is $$() iirc.

原型的 CSS 选择器方法是 $$() iirc。

For this example you could also use the native document.getElementsByName() method aswell.

对于此示例,您还可以使用本机 document.getElementsByName() 方法。

回答by Anirudh

You could use the following:

您可以使用以下内容:

 WebDriver driver=new FirefoxDriver();
    String nameAttribute=driver.findElement(By.cssSelector("Your css selector")).getAttribute("name")

回答by user3487861

In Java Selenium WebDriver there are 2 ways to do this

在 Java Selenium WebDriver 中有两种方法可以做到这一点

driver.findElement(By.name("myInput")).getText() driver.findElement(By.name("myInput")).getAttribute(value)

driver.findElement(By.name("myInput")).getText() driver.findElement(By.name("myInput")).getAttribute(value)