Java Selenium – 根据 value 属性选择一个 WebElement

huangapple go评论86阅读模式
英文:

Java Selenium - Select a WebElement based on value attribute

问题

我在想是否有一种方法可以根据 value 属性在网页上找到一个元素。

<option value="abc">这里是一些文本</option>
<option value="bcd">这里是一些文本</option>

我想我可以根据标签名称创建一个 WebElement 列表,并使用 .getAttribute("value") 遍历每个元素,但我想知道是否有一种更有效的方法来实现这一点,类似于您可以根据文本内容找到元素的方法:

driver.findElement(By.xpath("//*[contains(text(), '" + term + "')]"))
英文:

I was wondering if there was a way to find an element on a webpage based on the value attribute.

<option value="abc">Some text here</option>
<option value="bcd">Some text here</option>

I figured I could just create a list of WebElements based on the tag name and traverse each one using .getAttribute("value"), but I was wondering if there was a more effective way of doing this similar to the way you can find an element based on its text using:

driver.findElement(By.xpath("//*[contains(text(), '" + term + "')]"))

答案1

得分: 0

你可以这样做:

driver.findElement(By.cssSelector("[value=\"abc\"]"))

然后根据你要查找的内容更改"value"的值。

英文:

You can do this:

driver.findElement(By.cssSelector("[value=\"abc\"]"))

and you would change the value of value depending on what you were trying to find.

答案2

得分: 0

定位网页上 value="abc" 的元素,基于 abcvalue 属性,您可以使用以下任一 定位策略

  • [标签:CSS 选择器]:

      driver.findElement(By.cssSelector("option[value='abc']"))
    
  • [标签:XPath]:

      driver.findElement(By.xpath("//option[@value='abc']"))
    
英文:

To locate the element with value="abc" on a webpage `based on the value attribute of abc you can use either of the following Locator Strategies:

  • [tag:css-selectors]:

      driver.findElement(By.cssSelector("option[value='abc']"))
    
  • [tag:xpath]:

      driver.findElement(By.xpath("//option[@value='abc']"))
    

huangapple
  • 本文由 发表于 2020年3月4日 04:54:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/60515364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定