python - 为什么此解析器找不到使用 namespace 前缀的 XML 标记的内容?

标签 python xml xpath lxml xml-namespaces

我有这个 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&amp;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&amp;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/

相关文章:

python - 在python中导入外部 ".txt"文件

python - 如何根据索引替换子字符串?

javascript - 根据按下的字段使用 Jinja2 和 Flask 对对象列表进行排序

xml - 修改 SQL XML 列

java - Moxy 无法解码覆盖父类(super class)的子类字段

selenium - 如何在 perl $sel->click 下使用 Selenium 点击 Javascript

python - 多处理与 gevent

android - 如何对齐底部的 Include?

xpath - 是否可以使用 XPath 设置属性值?

excel - 在 FILTERXML 函数中使用 last()