繁体   English   中英

python元素树xml解析

[英]python element tree xml parsing

我正在使用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>"

以下代码可以解决问题。

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>'

您可以使用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

与@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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM