我有这个 XML 代码,来自这个链接:
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:nyt="http://www.nytimes.com/namespaces/rss/2.0" version="2.0">
<channel>
<item>
<title>‘This Did Not Go Well’: Inside PG&E’s Blackout Control Room</title>
<dc:creator>Ivan Penn</dc:creator>
<pubDate>Sat, 12 Oct 2019 17:03:11 +0000</pubDate>
</item>
</channel>
</rss>
当我尝试使用lxml并遵循xpath 和 XML namespaces 的文档对其进行解析时,解析器会找到标题(不使用命名空间),但不会找到作者/创建者,它会:
from lxml import html
xml = """
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:nyt="http://www.nytimes.com/namespaces/rss/2.0" version="2.0">
<channel>
<item>
<title>‘This Did Not Go Well’: Inside PG&E’s Blackout Control Room</title>
<dc:creator>Ivan Penn</dc:creator>
<pubDate>Sat, 12 Oct 2019 17:03:11 +0000</pubDate>
</item>
</channel>
</rss>
"""
rss = html.fromstring(xml)
items = rss.xpath("//item")
for item in items:
title = item.xpath("title")[0].text_content().strip()
print(title)
ns = {"dc" : "http://purl.org/dc/elements/1.1/"}
authors = item.xpath("dc:creator", namespaces = ns)
print(authors)
此代码打印:
这并不顺利':在 PG&E 的停电控制室内 []
由于它正确地找到了标题标签的内容,我认为它正在寻找单个<item>标签。我将命名空间传递给的方式有问题xpath吗?
编辑:无论我是否使用斜杠,结果都是相同的,即
ns = {"dc" : "http://purl.org/dc/elements/1.1/"}
ns = {"dc" : "http://purl.org/dc/elements/1.1"}
Smart猫小萌
相关分类