在 Python 中从给定的 html 中获取所有 xpath 列表的最佳方法是什么?

What is the best way to get a list of all xpaths from given html in Python?

提问人:Aeryes 提问时间:10/18/2023 更新时间:10/18/2023 访问量:38

问:

我希望从 Python 中给定的 html 中获取所有 xpath 的列表。我当前的实现仅使用 lxml 库为我提供了相对 xpath。我需要 xpaths 来使用 ids 和其他属性,这样我就可以在另一个应用程序的 Java Selenium 中使用这些 xpath。

    for element in html.iter():
        try:
            self.listOfXpathsFound.append(tree.getelementpath(element))
        except ValueError as val:
            count = count + 1
            print("ValueError: " + str(val))
            self.errorsDict["ValueError " + str(count)] = str(val)

我无法弄清楚如何在没有相对的情况下获得 xpath。有什么想法吗?

例:

使用 lxml etree 给出的 Xpath: //body//p//

必需的 xpath://@id=“para-one”

python xpath lxml 元素树

评论


答:

1赞 pensive 10/18/2023 #1

您似乎想在 Python 中使用 lxml 为 HTML 文档中的元素生成绝对 XPath 表达式。绝对 XPath 表达式包括用于唯一标识元素的 @id 等属性。

from lxml import html

# Parse your HTML document
html_content = "<your HTML content here>"
tree = html.fromstring(html_content)

# Get all elements with an "id" attribute
elements_with_id = tree.xpath('//*[@id]')

absolute_xpaths = []
for element in elements_with_id:
    # Construct the XPath with @id
    xpath = f'//*[@id="{element.get("id")}"]'
    absolute_xpaths.append(xpath)

for xpath in absolute_xpaths:
    print(xpath)

评论

0赞 Aeryes 10/18/2023
这几乎是我需要的。现在唯一的问题是,如果有多个情况使用相同的 ID 或类名。我怎样才能得到它们。
0赞 LMC 10/18/2023
//*表示所有/任何元素,因此如果寻找,您可能会有很多重复项。不过,不应该有重复@id。如果可能的话,可以进行改进tree.xpath('//*[@class]')xpath = f'{tree.getpath(element)}[@id="{element.get("id")}"]'