如何通过python中的文本获取xpath

jam*_*ccc -1 python

我们很容易通过 获取文本xpath,但是有什么方法可以xpath通过textPython?

例如。

 <html><h1>Hello World</h1></html>
Run Code Online (Sandbox Code Playgroud)

如何获得xpath通过Hello World

Sim*_*tis 5

对于同样的问题,我使用了这个函数。希望这个通用示例对您有所帮助。

你必须从给定的 url 定义函数:

def xpath_soup(element):
    """
    Generate xpath of soup element
    :param element: bs4 text or node
    :return: xpath as string
    """
    components = []
    child = element if element.name else element.parent
    for parent in child.parents:
        """
        @type parent: bs4.element.Tag
        """
        previous = itertools.islice(parent.children, 0,parent.contents.index(child))
        xpath_tag = child.name
        xpath_index = sum(1 for i in previous if i.name == xpath_tag) + 1
        components.append(xpath_tag if xpath_index == 1 else '%s[%d]' % (xpath_tag, xpath_index))
        child = parent
    components.reverse()
    return '/%s' % '/'.join(components)
Run Code Online (Sandbox Code Playgroud)

然后在 python 解释器上,运行:

>>> import re
>>> import itertools
>>> from bs4 import BeautifulSoup
>>> html = '<html><body><div><p>Hello World</p></div></body></html>'
>>> soup = BeautifulSoup(html, 'lxml')
>>> elem = soup.find(string=re.compile('Hello World'))
>>> xpath_soup(elem)
'/html/body/div/p'
Run Code Online (Sandbox Code Playgroud)

你有给定文本的 xpath