Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 793
pMan Avatar asked May 15 '12 07:05

pMan


People also ask

What is XPath in Selenium WebDriver?

XPath in Selenium WebDriver: Complete Tutorial. In Selenium automation, if the elements are not found by the general locators like id, class, name, etc. then XPath is used to find an element on the web page .

How to identify a webelement using XPath and JavaScript?

To identify a WebElement using xpath and javascript you have to use the evaluate () method which evaluates an xpath expression and returns a result. document.evaluate () returns an XPathResult based on an XPath expression and other given parameters. xpathExpression: The string representing the XPath to be evaluated.

What is the XPath of CSS path?

CSS path also locates elements having no name, class or ID. There are two types of XPath: It is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes made in the path of the element then that XPath gets failed.

What are the axes methods in Selenium WebDriver?

There are few axes methods commonly used in Selenium Webdriver like child, parent, ancestor, sibling, preceding, self, etc. XPath expression select nodes or list of nodes on the basis of attributes like ID , Name, Classname, etc. from the XML document as illustrated below.


1 Answers

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>
like image 162
yckart Avatar answered Oct 12 '22 02:10

yckart