我有这个 XML 代码,取自 this link :
<?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
解析它时并遵循 documentation for xpath and 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)
此代码打印:
This Did Not Go Well’: Inside PG&E’s Blackout Control Room []
由于它正确地找到了标题标签的内容,我认为它找到了个人 <item>
标签。我将命名空间传递给 xpath
的方式有问题吗? ?
编辑:无论我是否使用尾部斜杠,结果都是相同的,即
ns = {"dc" : "http://purl.org/dc/elements/1.1/"}
ns = {"dc" : "http://purl.org/dc/elements/1.1"}
最佳答案
HTML 解析器忽略命名空间。这是 Running HTML doctests 中的最后一句话lxml 文档中的部分:
The HTML parser notably ignores namespaces and some other XMLisms.
Another part文档说:
Also note that the HTML parser is meant to parse HTML documents. For XHTML documents, use the XML parser, which is namespace aware.
如果你改变它就会起作用
authors = item.xpath("dc:creator", namespaces = ns)
至
authors = item.xpath("creator")
但由于 RSS 不是 HTML,请考虑使用 XML 解析器(from lxml import etree
)。
关于python - 为什么此解析器找不到使用 namespace 前缀的 XML 标记的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58357807/