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

如何在python中通过文本获取xpath,python,Python,通过xpath获取文本对我们来说很容易,但是在Python中有没有办法通过文本获取xpath呢 例如 如何通过Hello World获取xpath?对于我使用的相同问题。 希望这个普通的例子能对你有所帮助 您必须从给定的url定义函数: def xpath_soup(element): """ Generate xpath of soup element :param element: bs4 text or node :return: xpath as stri

通过xpath获取文本对我们来说很容易,但是在Python中有没有办法通过文本获取xpath呢

例如


如何通过Hello World获取xpath?

对于我使用的相同问题。 希望这个普通的例子能对你有所帮助

您必须从给定的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)
然后在python intepreter上运行:

>>> 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'
您有给定文本的xpath

您可以使用contains

如果要使用标记内的文本获取元素,请使用 2.如果要获取包含文本“Hello World”的所有元素,请使用


我的一个主要问题已经解决:
>>> 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'
xpath('//h1[contains(text(),"Hello World")]')
xpath('//*[contains(text(),"Hello World")]')