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 に答える