简体   繁体   中英

How to find web element by xpath using javascript code in python selenium webdriver?

I would like to find web element by xpath executing javascript code in python and then click on it. Is this possible and how to do this?

You can use the following method (check the docs ):

find_element_by_xpath

Then, to click on the element you found, simply use:

element.click()

To find a WebElement by using in you have to use the evaluate() method which evaluates an xpath expression and returns a result.


document.evaluate()

document.evaluate() returns an XPathResult based on an XPath expression and other given parameters.

The syntax is:

var xpathResult = document.evaluate(
  xpathExpression,
  contextNode,
  namespaceResolver,
  resultType,
  result
);

Example

As an example the Search Box within the Google Home Page which can be identified uniquely using the xpath as //*[@name='q'] can also be identified from the Console using document.evaluate() and the xpath expression as follows:

document.evaluate("//*[@name='q']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

Snapshot:

document_evalute_xpath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM