Jér*_*eot 46 python attributes lxml find
我需要解析一个xml文件来提取一些数据.我只需要一些具有某些属性的元素,这里是一个文档示例:
<root>
<articles>
<article type="news">
<content>some text</content>
</article>
<article type="info">
<content>some text</content>
</article>
<article type="news">
<content>some text</content>
</article>
</articles>
</root>
Run Code Online (Sandbox Code Playgroud)
在这里,我想只获得"新闻"类型的文章.用lxml做最有效和最优雅的方法是什么?
我尝试使用find方法,但它不是很好:
from lxml import etree
f = etree.parse("myfile")
root = f.getroot()
articles = root.getchildren()[0]
article_list = articles.findall('article')
for article in article_list:
if "type" in article.keys():
if article.attrib['type'] == 'news':
content = article.find('content')
content = content.text
Run Code Online (Sandbox Code Playgroud)
Dev*_*rre 74
你可以使用xpath,例如 root.xpath("//article[@type='news']")
此xpath表达式将返回<article/>具有值"news"的"type"属性的所有元素的列表.然后,您可以迭代它以执行您想要的操作,或者将其传递到任何地方.
要获得文本内容,您可以像这样扩展xpath:
root = etree.fromstring("""
<root>
<articles>
<article type="news">
<content>some text</content>
</article>
<article type="info">
<content>some text</content>
</article>
<article type="news">
<content>some text</content>
</article>
</articles>
</root>
""")
print root.xpath("//article[@type='news']/content/text()")
Run Code Online (Sandbox Code Playgroud)
这将输出['some text', 'some text'].或者,如果您只是想要内容元素,那么它将是"//article[@type='news']/content"- 等等.
Kji*_*jir 10
仅供参考,您可以通过以下方式获得相同的结果findall:
root = etree.fromstring("""
<root>
<articles>
<article type="news">
<content>some text</content>
</article>
<article type="info">
<content>some text</content>
</article>
<article type="news">
<content>some text</content>
</article>
</articles>
</root>
""")
articles = root.find("articles")
article_list = articles.findall("article[@type='news']/content")
for a in article_list:
print a.text
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51608 次 |
| 最近记录: |