【问题标题】:python element tree xml parsingpython元素树xml解析
【发布时间】:2012-11-16 07:42:23
【问题描述】:

我正在使用 Python 元素树来解析 xml 文件

假设我有一个这样的 xml 文件..

<html>
<head>
    <title>Example page</title>
</head>
<body>
    <p>hello this is first paragraph </p>
    <p> hello this is second paragraph</p>
</body>
</html>

有什么方法可以提取带有完整 p 标签的正文,如

desired= "<p>hello this is first paragraph </p> <p> hello this is second paragraph</p>"

【问题讨论】:

    标签: python xml-parsing


    【解决方案1】:

    下面的代码可以解决问题。

    import xml.etree.ElementTree as ET
    
    root = ET.fromstring(doc)  # doc is a string containing the example file
    body = root.find('body')
    desired = ' '.join([ET.tostring(c).strip() for c in body.getchildren()])
    

    现在:

    >>> desired
    '<p>hello this is first paragraph </p> <p> hello this is second paragraph</p>'
    

    【讨论】:

    • 不仅是 p 标签,还可以有任何类似的 标签 标签任何建议 ...
    • 这将拉出任何身体的孩子,无论标签类型如何。我认为我在代码中使用了p 可能会造成混淆。这与&lt;p&gt; 标签无关,我将更改代码以使其清晰。但是,当正文包含不在子元素内的文本时,此解决方案将不起作用。
    【解决方案2】:

    你可以使用lxml库,lxml

    所以,这段代码会对你有所帮助。

    import lxml.html
    
    htmltree = lxml.html.parse('''
    <html>
    <head>
    <title>Example page</title>
    </head>
     <body>
    <p>hello this is first paragraph </p>
    <p> hello this is second paragraph</p>
    </body>
    </html>''')
    p_tags = htmltree.xpath('//p')
    p_content = [p.text_content() for p in p_tags]
    
    print p_content
    

    【讨论】:

      【解决方案3】:

      与@DavidAlber 略有不同的方式,可以轻松选择孩子:

      from xml.etree import ElementTree
      
      tree = ElementTree.parse("example.xml")
      body = tree.findall("/body/p")
      
      result = []
      for elem in body:
           result.append(ElementTree.tostring(elem).strip())
      
      print " ".join(result)
      

      【讨论】:

        猜你喜欢
        • 2019-10-26
        • 1970-01-01
        • 1970-01-01
        • 2011-06-11
        • 1970-01-01
        • 1970-01-01
        • 2011-12-22
        • 2017-10-09
        • 1970-01-01
        相关资源
        最近更新 更多