【问题标题】:How to extract text including inline elements and the xpath to that element of the HTML page in Python如何在 Python 中提取包括内联元素和 HTML 页面该元素的 xpath 在内的文本
【发布时间】:2021-03-13 10:05:56
【问题描述】:

我正在处理一个 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>
                <span>This is the</span> 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: <span>This is the</span> example HTML

【问题讨论】:

    标签: python html web-scraping lxml


    【解决方案1】:
       import xmltodict
    import json
    def flatten_json(y):
        #creates Xpath for each tag with counts
        out = {}
        def flatten(x, name=''):
            if type(x) is dict:
                for a in x:
                    flatten(x[a], name + a + "/")
            elif type(x) is list:
                i = 0
                for a in x:
                    flatten(a, name + str(i) + "/")
                    i += 1
            else:
                out[name] = x
        flatten(y)
        print(out)
    
    with open("test_django.html") as fd:
        doc = xmltodict.parse(fd.read())
    output_dict = json.loads(json.dumps(doc))
    flatten_json(output_dict)
    

    上面的代码给了我以下输出:

    {'html/head/title/': '演示页面', 'html/body/div/section/h1/': '你好世界', 'html/body/div/div/0/p/': '希望你们一切都好', 'html/body/div/div/1/p/span/': '这是', 'html/body/div/div/1/p/#text/': '示例 HTML'}

    对于 span 标签,如果你想以不同的方式显示,那么你必须相应地添加自己的逻辑

    【讨论】:

      猜你喜欢
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-06
      • 2013-01-15
      • 2018-03-26
      • 2015-04-27
      • 1970-01-01
      相关资源
      最近更新 更多