title: BeautifulSoup extract XPATH or CSS Path of node
body: <p>I want to extract some data from HTML and then be able to highlight extracted elements on client side without modifying source html. And XPath or CSS Path looks great for this. <strong>Is that possible to extract XPATH or CSS Path directly from BeautifulSoup?</strong><br>
  Right now I use marking of target element and then lxml lib to extract xpath, which is very bad for performance. I know about <code>BSXPath.py</code> -- it's does not work with BS4.
  Solution with rewriting everything to use native lxml lib is not acceptable due to complexity.</p>
  
  <pre><code>import bs4
  import cStringIO
  import random
  from lxml import etree
  
  
  def get_xpath(soup, element):
    _id = random.getrandbits(32)
    for e in soup():
      if e == element:
        e['data-xpath'] = _id
        break
    else:
      raise LookupError('Cannot find {} in {}'.format(element, soup))
    content = unicode(soup)
    doc = etree.parse(cStringIO.StringIO(content), etree.HTMLParser())
    element = doc.xpath('//*[@data-xpath="{}"]'.format(_id))
    assert len(element) == 1
    element = element[0]
    xpath = doc.getpath(element)
    return xpath
  
  soup = bs4.BeautifulSoup('&lt;div id=i&gt;hello, &lt;b id=i test=t&gt;world!&lt;/b&gt;&lt;/div&gt;')
  xpath = get_xpath(soup, soup.div.b)
  assert '//html/bodydiv/b' == xpath
  </code></pre>