selenium中的WebElement选择attr

naf*_*fas 1 java selenium xpath css-selectors

我喜欢使用seleniumin 在页面中选择此标记java

<input class="btn btn-success addReportBtn" type="submit" />
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所尝试的:

driver.findElement(By.xpath("//input[type=submit]"));
driver.findElement(By.cssSelector("//input[@type='submit']"));
Run Code Online (Sandbox Code Playgroud)

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

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

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

如果我使用Jsoup我可以通过以下方式轻松实现:

System.out.println(document.select("input[type=submit]"));
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

ale*_*cxe 5

正如@Jason所指出的,你正在认真地混合使用XPath表达式和CSS选择器语法.正确的表达方式是:

driver.findElement(By.xpath("//input[@type='submit']"));
driver.findElement(By.cssSelector("input[type=submit]"));
Run Code Online (Sandbox Code Playgroud)

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

driver.findElement(By.cssSelector("input.addReportBtn"));
Run Code Online (Sandbox Code Playgroud)

这也为可读性提供了优势.