【问题标题】:How to extract text and the xpath to that element of the HTML page in Python如何在 Python 中提取 HTML 页面的该元素的文本和 xpath
【发布时间】:2021-03-13 08:04:49
【问题描述】:

我正在处理一个 Django 项目,我需要在其中提取所有包含文本的元素以及该元素的 xPath。 例如:

<html>
<head>
    <title>
        The Demo page
    </title>
</head>

<body>
    <div>
        <section>
            <h1> Hello world
            </h1>
        </section>
        <div>
            <p>
                Hope you all are doing well,
            </p>
        </div>
        <div>
            <p>
                This is the example HTML
            </p>
        </div>
    </div>
</body>
</html>

输出应该是这样的:

/head/title: The Demo Page
/body/div/section/h1: Hello world!
/body/div/div[1]/p: Hope you all are doing well,
/body/div/div[2]/p: This is the example HTML

【问题讨论】:

    标签: python html xpath web-scraping lxml


    【解决方案1】:

    这样的事情应该可以工作:

    from lxml import etree
    html = """[your html above]"""
    
    root = etree.fromstring(html)
    targets = root.xpath('//text()[normalize-space()]/..')
    tree = etree.ElementTree(root)
    
    for target in targets:
        print(tree.getpath(target),target.text.strip())
    

    输出:

    /html/head/title The Demo page
    /html/body/div/section/h1 Hello world
    /html/body/div/div[1]/p Hope you all are doing well,
    /html/body/div/div[2]/p This is the example HTML
    

    【讨论】:

    • 您的回答对于上述 HTML 来说效果很好,但如果 &lt;p&gt; 标记中的文本类似于 &lt;div&gt;&lt;p&gt;&lt;span&gt;This is the&lt;/span&gt; example HTML&lt;/p&gt;&lt;/div&gt;,则它会失败
    • 我们怎样才能得到这个文本为&lt;span&gt;This is the &lt;/span&gt; example HTML
    • @ShahidTariq 首先,您的示例 html 中没有 &lt;span&gt;。其次,无论如何,这是一个不同的问题,根据 StackOverflow 政策,您可能应该使用新的示例 html 将其作为另一个问题发布。
    • 谢谢!但无论如何,如果您能帮助自己在这里回答问题,我们将不胜感激。
    • @ShahidTariq 恐怕不行;您对问题的编辑所做的更改以及您评论中的新问题可能需要对所有内容采取不同的方法。正如我所说,最好撤消对原始问题的编辑并发布一个新问题。
    猜你喜欢
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多