[英]Locate web elements with JavaScript by CSS Selector or XPath?
While creating Selenium automation tests sometimes we need to retrieve a web element with JavaScript, not with Selenium driver.findElement
.在创建 Selenium 自动化测试时,有时我们需要使用 JavaScript 检索 web 元素,而不是使用
driver.findElement
So, I know we can do something like所以,我知道我们可以做类似的事情
javaScript = "document.getElementsByClassName('myClassName')[0].click();"
driver.execute_script(javaScript)
I see we can locate elements in this way ByClassName
, ByName
, ByTagName
and BytagNameNS
but in most cases element can be uniquely located with CSS Selector or XPath only while I couldn't see such way in documentations andtutorials .我看到我们可以通过
ByClassName
、 ByName
、 ByTagName
和BytagNameNS
这种方式定位元素,但在大多数情况下,元素可以使用 CSS 选择器或 XPath 唯一定位,而我在文档和教程中看不到这种方式。
So, I'm wondering is it possible to locate web elements with JavaScript by XPath or CSS Selectors?所以,我想知道是否有可能通过 XPath 或 Z2C56CZ3686155AF75A60A0F6E9D80C1F7EDD3E9Z 找到 web 元素?
document.querySelector() //for single node with css like path or selector
document.querySelectorAll() //for multiple nodes
To select by ID:通过 ID 发送至 select:
document.querySelector('#ID') //returns single element
document.querySelectorAll('#ID') //returns node list, you may need to use forEach
To select by class: class 致 select:
document.querySelector('.class') //returns single element
document.querySelectorAll('.class') //returns node list, you may need to use forEach
To select inside div by class: select 由 class 在 div 内:
document.querySelector('div > .class') //returns single element
document.querySelectorAll('div > .class') //returns node list, you may need to use forEach
Here is the documentation这是文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.