【问题标题】:How to parse an xml feed using python?如何使用 python 解析 xml 提要?
【发布时间】:2012-10-14 02:51:01
【问题描述】:

我正在尝试解析这个 xml (http://www.reddit.com/r/videos/top/.rss) 并且在这样做时遇到了麻烦。我正在尝试将 youtube 链接保存在每个项目中,但由于“频道”子节点而遇到麻烦。我如何达到这个级别,然后我可以遍历这些项目?

#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])

【问题讨论】:

    标签: python xml parsing


    【解决方案1】:

    你可以试试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])
    

    【讨论】:

      【解决方案2】:

      我使用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
      

      【讨论】:

        猜你喜欢
        • 2012-02-13
        • 1970-01-01
        • 1970-01-01
        • 2012-11-08
        • 2016-08-26
        • 1970-01-01
        • 2015-03-28
        • 2016-01-17
        • 2014-03-18
        相关资源
        最近更新 更多