0

I have an HTML document, and I know a value that exists in the document. Using python how would I get the Xpath to that value? (not the value at the Xpath) The value may occur more than once so a list of a way to iterate would be useful.

For example if I want the Xpath to "bytearray":

    http://en.wikipedia.org/wiki/Python_(programming_language)
it is (using google Chrome)
    //*[@id="mw-content-text"]/table[2]/tbody/tr[3]/td[1]/code

Another example

    from lxml import etree
    import StringIO

    # Example of get value given Xpath (I know how to do this)
    f = StringIO.StringIO('<foo><bar>xyz</bar></foo>')
    tree = etree.parse(f)
    r = tree.xpaths('/foo/bar')
    print(r[0].text)
    >>> xyz

    # Example get Xpath given value. How do I do this ?
    value = 'xyz'
    path = getXpath(value)
    for p in path:
        print(p)
    >>> /foo/bar

I am not stuck on using Xpath, my purpose is to use some type of location information of the value I know is on a page to retrieve an unknown value on a page with the same layout. I don't what to do it manually because there are hundreds of (value, location) pairs.

Vincent
  • 1,579
  • 4
  • 23
  • 38
  • you mean something like http://lxml.de/xpathxslt.html ? – Guy Gavriely Jan 15 '14 at 02:12
  • The context of this is very unclear, can you include some more code, and also, BeautifulSoup doesn't support XPath. –  Jan 15 '14 at 02:29
  • @Guy, Maybe more specifically your are referring to find(pattern) (see link) This does not return the full Xpath the the "pattern", or am I wrong? http://effbot.org/zone/element.htm#searching-for-subelements – Vincent Jan 15 '14 at 02:38
  • 1
    pls see this http://stackoverflow.com/questions/1577293/how-to-get-path-of-an-element-in-lxml – Guy Gavriely Jan 15 '14 at 02:43
  • @Guy Thats great!. This finds all text, I can obviously sort through it for what I want, is it possible to limit it to a specific text. Doing something like //text()='Example' seems to return true or false. – Vincent Jan 15 '14 at 03:23
  • 1
    sure, xpath is very powerful, see http://stackoverflow.com/questions/3206975/xpath-selecting-elements-that-equal-a-value – Guy Gavriely Jan 15 '14 at 03:29

0 Answers0