0

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

3 回答 3

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>'
于 2012-11-16T07:54:25.107 回答
0

你可以使用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
于 2012-11-16T07:54:12.177 回答
0

与@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)
于 2012-11-16T08:09:49.813 回答