greenszpila
greenszpila

Reputation: 203

Python/Selenium webdriver . Find an element on the page and prints/return it's xpath

I have a script which is searching for a text string on the webpage

el = driver.find_elements_by_xpath("//*[contains(text(), 'Sample_Text')]")

It returns what I have expected when I print the result.

print (el[-1].text)

for x in el:
  print (x.xpath)
  print('found sample text:\n',x.text)

Is it possible to add a line that will print/return the xpath of the webelement?, I need to get the xpath of the el[-1] or the x in the For loop. Obviously x.xpath is giving me error:

AttributeError: 'WebElement' object has no attribute 'xpath'

I know how to get the xpath when inspecting the code. But i would like the script to get it for me. For the webelement which matches the text string.

thanks,

Upvotes: 1

Views: 415

Answers (1)

Sureshmani Kalirajan
Sureshmani Kalirajan

Reputation: 1938

There is no pre-existing method to retrieve the xpath string from the element. However it is possible to construct one. here is an example using lxml,

import lxml
from lxml import html

# get the page source from the driver.
tree = html.fromstring(driver.page_source)
el = tree.xpath("//*[contains(text(), 'Sample_Text')]")

# This should print the direct xpath to the element.
myElementXpath = el.getroottree().getpath(el)
print(myElementXpath )

Now you can use this xpath in driver to perform actions.

Upvotes: 1

Related Questions