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

问题描述 投票:0回答:1

我希望从Python中的给定html中获取所有xpath的列表。我当前的实现仅使用 lxml 库为我提供相对 xpath。我需要 xpath 来使用 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 elementtree
1个回答
0
投票

您似乎想在 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)
© www.soinside.com 2019 - 2024. All rights reserved.