有没有办法在Selenium WebDriver中使用JavaScript通过XPath获取元素? [英] Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

查看:195
本文介绍了有没有办法在Selenium WebDriver中使用JavaScript通过XPath获取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似的东西:

I am looking for something like:

getElementByXpath(//html[1]/body[1]/div[1]).innerHTML

我需要使用JS获取元素的innerHTML(在Selenium中使用它) WebDriver / Java,因为WebDriver本身找不到它,但是如何?

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?

我可以使用ID属性,但并非所有元素都有ID属性。

I could use ID attribute, but not all elements have ID attribute.

[已固定]

我正在使用jsoup在Java中完成它。这符合我的需要。

I am using jsoup to get it done in Java. That works for my needs.

推荐答案

你可以使用 document.evaluate


评估XPath表达式字符串,并在可能的情况下返回
指定类型的结果。

Evaluates an XPath expression string and returns a result of the specified type if possible.

w3标准化和整个文档: 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

还有一个关于mozilla开发者网络的精彩介绍: https:/ /developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate

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

这篇关于有没有办法在Selenium WebDriver中使用JavaScript通过XPath获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆