Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

javascript - 有没有一种方法可以使用Selenium WebDriver中的JavaScript通过XPath获取元素?(Is there a way to get element by XPath using JavaScript in Selenium WebDriver?)

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?(我需要使用JS获取元素的innerHTML(要在Selenium WebDriver / Java中使用它,因为WebDriver本身无法找到它),但是如何?) I could use ID attribute, but not all elements have ID attribute.(我可以使用ID属性,但并非所有元素都具有ID属性。) [FIXED]([固定]) I am using jsoup to get it done in Java.(我正在使用jsoup在Java中完成它。) That works for my needs.(这符合我的需求。)   ask by pMan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use document.evaluate :(您可以使用document.evaluate :)

Evaluates an XPath expression string and returns a result of the specified type if possible.(计算XPath表达式字符串,并在可能的情况下返回指定类型的结果。) It is w3-standardized and whole documented: https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate(它是W3标准化的,并且完整记录在案: https : //developer.mozilla.org/zh-CN/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(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(Mozilla开发人员网络上也有出色的介绍: https : //developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate) Alternative version, using XPathEvaluator :(使用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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...