有没有办法在 Selenium WebDriver 中使用 JavaScript 通过 XPath 获取元素? [英] Is there a way to get element by XPath using JavaScript in Selenium WebDriver?
问题描述
我正在寻找类似的东西:
getElementByXpath(//html[1]/body[1]/div[1]).innerHTML
我需要使用 JS 获取元素的 innerHTML(在 Selenium WebDriver/Java 中使用它,因为 WebDriver 无法找到它本身),但是如何?
我可以使用 ID 属性,但并非所有元素都有 ID 属性.
[已修复]
我正在使用 jsoup 在 Java 中完成它.这适合我的需求.
你可以使用document.evaluate
:
计算 XPath 表达式字符串并返回结果如果可能,请指定类型.
它是 w3 标准化 和整个文档:https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate
function getElementByXpath(path) {返回 document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;}console.log( getElementByXpath("//html[1]/body[1]/div[1]"));
foo
https://gist.github.com/yckart/6351935
还有关于 mozilla 开发者网络的精彩介绍:https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate
<小时>替代版本,使用XPathEvaluator
:
function getElementByXPath(xpath) {返回新的 XPathEvaluator().createExpression(xpath).evaluate(文档,XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue}console.log( getElementByXPath("//html[1]/body[1]/div[1]"));
<div>foo/bar</div>
I am looking for something like:
getElementByXpath(//html[1]/body[1]/div[1]).innerHTML
I need to get the innerHTML of elements using JS (to use that in Selenium WebDriver/Java, since WebDriver can't find it itself), but how?
I could use ID attribute, but not all elements have ID attribute.
[FIXED]
I am using jsoup to get it done in Java. That works for my needs.
You can use document.evaluate
:
Evaluates an XPath expression string and returns a result of the specified type if possible.
It is w3-standardized and whole documented: https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate
function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
console.log( getElementByXpath("//html[1]/body[1]/div[1]") );
<div>foo</div>
https://gist.github.com/yckart/6351935
There's also a great introduction on mozilla developer network: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate
Alternative version, using XPathEvaluator
:
function getElementByXPath(xpath) {
return new XPathEvaluator()
.createExpression(xpath)
.evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE)
.singleNodeValue
}
console.log( getElementByXPath("//html[1]/body[1]/div[1]") );
<div>foo/bar</div>
这篇关于有没有办法在 Selenium WebDriver 中使用 JavaScript 通过 XPath 获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!