【问题标题】:WebElement in selenium select with attr硒中的WebElement选择与attr
【发布时间】:2016-02-22 23:58:40
【问题描述】:

我喜欢在java中使用selenium在页面中选择这个标签

<input class="btn btn-success addReportBtn" type="submit" />

这是我迄今为止尝试过的:

driver.findElement(By.xpath("//input[type=submit]"));
driver.findElement(By.cssSelector("//input[@type='submit']"));

我分别得到了这两个例外:

org.openqa.selenium.NoSuchElementException:没有这样的元素:无法找到元素:{"method":"xpath","selector":"input[type=submit]"}

org.openqa.selenium.InvalidSelectorException:无效选择器:指定了无效或非法的选择器

如果我使用Jsoup,我可以通过以下方式轻松获得它:

System.out.println(document.select("input[type=submit]"));

我做错了什么?

【问题讨论】:

    标签: java selenium xpath css-selectors


    【解决方案1】:

    试试这些:

    driver.findElement(By.xpath("//input[@type='submit']"));
    driver.findElement(By.cssSelector("input[type='submit']"));
    

    【讨论】:

      【解决方案2】:

      正如@Jason 所指出的,您严重混淆了 XPath 表达式和 CSS 选择器语法。正确的表达方式是:

      driver.findElement(By.xpath("//input[@type='submit']"));
      driver.findElement(By.cssSelector("input[type=submit]"));
      

      请注意,我不会只检查按钮类型,因为通常一个页面上有多个提交按钮。有 addReportBtn 类我会依赖定位器:

      driver.findElement(By.cssSelector("input.addReportBtn"));
      

      这也增加了可读性。

      【讨论】:

      • 我只是要编辑我的答案并提到按类而不是类型选择元素。赞成。 :)
      • 我现在感觉像个笨蛋,按班级选择是最好的
      • @nafas - alecxe 给出了更好的答案。请接受他的而不是我的。
      • 我绝对同意input.addReportBtn。那个类似乎很具体。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      相关资源
      最近更新 更多