如何使用Python解析XML源?

5

我正在尝试解析这个xml文件(http://www.reddit.com/r/videos/top/.rss),但是遇到了一些问题。我想要保存每个条目中的YouTube链接,但是由于"channel"子节点的存在,我遇到了麻烦。我该如何进入这个级别,以便我可以遍历这些条目?

#reddit parse
reddit_file = urllib2.urlopen('http://www.reddit.com/r/videos/top/.rss')
#convert to string:
reddit_data = reddit_file.read()
#close file because we dont need it anymore:
reddit_file.close()

#entire feed
reddit_root = etree.fromstring(reddit_data)
channel = reddit_root.findall('{http://purl.org/dc/elements/1.1/}channel')
print channel

reddit_feed=[]
for entry in channel:   
    #get description, url, and thumbnail
    desc = #not sure how to get this

    reddit_feed.append([desc])
2个回答

7
你可以尝试使用findall('channel/item')
import urllib2
from xml.etree import ElementTree as etree
#reddit parse
reddit_file = urllib2.urlopen('http://www.reddit.com/r/videos/top/.rss')
#convert to string:
reddit_data = reddit_file.read()
print reddit_data
#close file because we dont need it anymore:
reddit_file.close()

#entire feed
reddit_root = etree.fromstring(reddit_data)
item = reddit_root.findall('channel/item')
print item

reddit_feed=[]
for entry in item:   
    #get description, url, and thumbnail
    desc = entry.findtext('description')  
    reddit_feed.append([desc])

4

我使用 Xpath 表达式为您编写了以下内容(已经测试成功):

from lxml import etree
import urllib2

headers = { 'User-Agent' : 'Mozilla/5.0' }
req = urllib2.Request('http://www.reddit.com/r/videos/top/.rss', None, headers)
reddit_file = urllib2.urlopen(req).read()

reddit = etree.fromstring(reddit_file)

for item in reddit.xpath('/rss/channel/item'):
    print "title =", item.xpath("./title/text()")[0]
    print "description =", item.xpath("./description/text()")[0]
    print "thumbnail =", item.xpath("./*[local-name()='thumbnail']/@url")[0]
    print "link =", item.xpath("./link/text()")[0]
    print "-" * 100

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接