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?
Asked
Active
Viewed 2,093 times
2 Answers
2
To find a WebElement by xpath using javascript 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 google-chrome-devtools Console using document.evaluate()
and the xpath expression as follows:
document.evaluate("//*[@name='q']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
Snapshot:

undetected Selenium
- 183,867
- 41
- 278
- 352
-1
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()

Hussein Fawzy
- 366
- 2
- 16
-
1I know I can find web element by using your above code but this is not what I've asked for. Anyway thanks for your response. – beginsql Jul 25 '20 at 15:14
-
nice, unless he asks about JAVASCRIPT CODE – user2678074 Dec 10 '21 at 09:17