13

I am using selenium and I need to find the XPaths of some selenium web elements.

For example:

import selenium.webdriver
driver = selenium.webdriver.Firefox()

element  = driver.find_element_by_xpath(<some_xpath>)
elements = element.find_elements_by_xpath(<some_relative_xpath>)

for e in elements:
    print e.get_xpath()

I know I can't get the XPath from the element itself, but is there a nice way to get it anyway?

I tried using lxml to parse the HTML, but it doesn't recognize the XPath, <some_xpath>, I passed, even though driver.find_element_by_xpath(<some_xpath>) did manage to find that element.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
ro.e
  • 319
  • 1
  • 3
  • 13
  • Are you trying to find an element from the xpath or are you trying to generate the xpath given an element? The beginning seems to suggest the latter but the end of your question suggests the former. If it is the former you could provide the xpath you are trying and potentially the html/xml snippet? – Bob Jun 25 '14 at 14:52
  • 1
    You cannot generate an xpath from the element since there are multiple ways to find an element by xpath. – alecxe Jun 25 '14 at 14:53
  • I want to find the xpath of a given element. I know there are multiple xpath representation for a given element, but any representation is fine by me. – ro.e Jun 25 '14 at 15:06

1 Answers1

8

lxml can auto-generate an absolute xpath for you using getpath() method.

Example (using wikipedia main page, getting xpath expression for the logo):

import urllib2
from lxml import etree

data = urllib2.urlopen("https://en.wikipedia.org")
tree = etree.parse(data)
element = tree.xpath('//div[@id="p-logo"]/a')[0]
print tree.getpath(element)

Prints:

/html/body/div[4]/div[2]/div[1]/a
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195