【问题标题】:how to locate an element by value using css selector in webdriver?如何在 webdriver 中使用 css 选择器按值定位元素?
【发布时间】:2014-09-21 23:35:46
【问题描述】:

对于下面的元素,如何使用 css 选择器通过 td 的值找到它?在这种情况下,它是“唯一文本”

<td class="someclass" colspan="3">
   unique text
</td>

【问题讨论】:

    标签: selenium-webdriver css-selectors


    【解决方案1】:

    您可以使用动态 xpath 或动态 css 定位 WebElement

    css-

    WebElement css = driver.findElement(By.cssSelector("td#someclass"));
    

    xpath-

    WebElement xpath = driver.findElement(By.xpath("//td[text,'unique text']"));
    

    【讨论】:

      【解决方案2】:

      您可以使用 CSS 方法通过其类名来定位元素。

      css=".someclass"
      

      查看更多示例here.

      【讨论】:

        【解决方案3】:

        WebElement 元素 = driver.findElement(By.cssSelector("input[value='要取的值']")); //这一行是选择单选按钮

        element.click();

        【讨论】:

          【解决方案4】:

          使用以下 XPath 总能给我预期的结果和性能。看我的另一个答案here

          //td[.='unique text'] 
          

          【讨论】:

            【解决方案5】:

            你可以使用这样的东西,

            使用 CSS 选择器,

             By.cssSelector("td[class='someclass'][value='unique text']");
            

            有关使用 css 选择器的更多信息,See here

            【讨论】:

            • @saifur 如果您要通过其值(唯一文本)查找元素,您需要找到它的位置,在这种情况下,它位于具有特定类的“td”内(一些类)
            • 这只有在你的 节点上有一个名为“value”的属性时才有效。 CSS 中没有值选择器。
            【解决方案6】:

            我们可以像下面这样创建一个 XPath:

            //td[contains(text(), 'unique text')]
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-09-08
              • 2021-04-15
              • 1970-01-01
              • 2018-03-06
              • 2019-07-20
              • 2019-08-31
              • 2014-08-07
              相关资源
              最近更新 更多