有没有办法在 HTML 文件和 return 它的 XPath 中找到一个字符串?

Is there a way to find a string in a HTML file and return its XPath?

我正在尝试在抓取工具中进行逆向工程以生成模型来提取数据。

所以,我知道页面的标题,我想在 HTML 代码中查找它,然后 return XPath 或 CSS 选择器到此位置。

我正在使用 Scrapy in my project, but, for this reverse engineering, I thought maybe Beautiful Soup 4 结合 lxml 解析器也可以帮助我。我只是还没有找到任何关于它的文档。

有谁知道有没有办法做到这一点?

如果你真的使用 lxml,你可以使用 getpath()...

from lxml import etree

xml = """
<doc>
    <one>
        <two>
            <test>foo</test>
        </two>
        <two>
            <test>bar</test>
        </two>
    </one>
</doc>
"""

tree = etree.fromstring(xml)

for match in tree.xpath("//*[contains(text(),'bar')]"):
    print(etree.ElementTree(tree).getpath(match))

这会打印:

/doc/one/two[2]/test