我正在使用 Selenium 进行测试自动化,通常使用 css 选择器来定位元素。然而最近,我遇到了一个奇怪的问题。我注意到,在某些情况下,当我在浏览器控制台中测试时,CSS 选择器工作正常。例如,要从众多按钮中选择一个特定按钮,我会这样做:
(1) $("div.v-app[id^='v-discussions'] .v-button-caption:contains('Add')")
但是当我实际在 Selenium 中使用时它会返回一个错误:
Caused by: org.openqa.selenium.InvalidSelectorException: The given selector div.v-app[id^='v-discussions'] .v-button-caption:contains('Add') is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: An invalid or illegal selector was specified
我还使用 querySelector
尝试了该字符串,但收到“非法字符串”错误:
(2) document.querySelectorAll("div.v-app[id^='v-discussions'] .v-button-caption:contains('Add')")
为什么会发生这种情况?
附注
这是每个元素的样子:
<span class="v-button-caption">Add Comment</span>
最佳答案
那就去吧:
WebElement element = driver.findElement(By.className("v-button-caption"));
我在 Selenium Webdriver 中使用它并且对我来说工作得很好
关于javascript - css 选择器在浏览器中有效,但在 Selenium 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32085650/