-
-
Save binfeng/2ad6c1c1e6cbb4e02aee5547a5aabc63 to your computer and use it in GitHub Desktop.
Generate unique XPATH for BeautifulSoup element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
def xpath_soup(element): | |
# type: (typing.Union[bs4.element.Tag, bs4.element.NavigableString]) -> str | |
""" | |
Generate xpath from BeautifulSoup4 element. | |
:param element: BeautifulSoup4 element. | |
:type element: bs4.element.Tag or bs4.element.NavigableString | |
:return: xpath as string | |
:rtype: str | |
Usage | |
----- | |
>>> import bs4 | |
>>> html = ( | |
... '<html><head><title>title</title></head>' | |
... '<body><p>p <i>1</i></p><p>p <i>2</i></p></body></html>' | |
... ) | |
>>> soup = bs4.BeautifulSoup(html, 'html.parser') | |
>>> xpath_soup(soup.html.body.p.i) | |
'/html/body/p[1]/i' | |
>>> import bs4 | |
>>> xml = '<doc><elm/><elm/></doc>' | |
>>> soup = bs4.BeautifulSoup(xml, 'lxml-xml') | |
>>> xpath_soup(soup.doc.elm.next_sibling) | |
'/doc/elm[2]' | |
""" | |
components = [] | |
child = element if element.name else element.parent | |
for parent in child.parents: # type: bs4.element.Tag | |
siblings = parent.find_all(child.name, recursive=False) | |
components.append( | |
child.name if 1 == len(siblings) else '%s[%d]' % ( | |
child.name, | |
next(i for i, s in enumerate(siblings, 1) if s is child) | |
) | |
) | |
child = parent | |
components.reverse() | |
return '/%s' % '/'.join(components) | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod(verbose=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment