在Python中使用Elementtree解析RSS [英] Parsing RSS with Elementtree in Python

查看:74
本文介绍了在Python中使用Elementtree解析RSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何使用Python中的Elementtree在XML中搜索特定于名称空间的标记?

How do you search for namespace-specific tags in XML using Elementtree in Python?

我有一个XML / RSS文档,例如:

I have an XML/RSS document like:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:wp="http://wordpress.org/export/1.0/"
>
<channel>
    <title>sometitle</title>
    <pubDate>Tue, 28 Aug 2012 22:36:02 +0000</pubDate>
    <generator>http://wordpress.org/?v=2.5.1</generator>
    <language>en</language>
    <wp:wxr_version>1.0</wp:wxr_version>
    <wp:category><wp:category_nicename>apache</wp:category_nicename><wp:category_parent></wp:category_parent><wp:cat_name><![CDATA[Apache]]></wp:cat_name></wp:category>
</channel>
</rss>

但是当我尝试通过以下方式找到所有 wp:category标签时:

But when I try and find all "wp:category" tags by doing:

import xml.etree.ElementTree as xml
tree = xml.parse(fn)
doc = tree.getroot()
categories = doc.findall('channel/wp:category')

错误:

SyntaxError: prefix 'wp' not found in prefix map

搜索任何非命名空间特定的字段都可以。我在做什么错了?

Searching for any non-namespace specific fields works just fine. What am I doing wrong?

推荐答案

您需要处理名称空间前缀,方法是使用iterparse并直接处理该事件,或者在解析之前显式声明您感兴趣的前缀。根据您要尝试执行的操作,我会在懒惰的时候承认我只是在解析XML之前用字符串replace去除了所有前缀。

You need to handle the namespace prefixes, either by using iterparse and handling the event directly or by explicitly declaring the prefixes you're interested in before parsing. Depending on what you're trying to do, I will admit in my lazier moments I just strip all the prefixes out with a string replace before parsing the XML.

编辑: 类似的问题可能会有帮助。

这篇关于在Python中使用Elementtree解析RSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆