实用的 Python 之 feedparser

feedparser 号称是一个 universal feed parser,使用它我们可轻松地实现从任何 RSS 或 Atom 订阅源得到标题、链接和文章的条目了。

>>> import feedparser
     
     
     
     
  • 1
  • 1

为了建立直观,首先来看一个标准的 item:

<item>
<title>警方公布嫌犯犯罪证据]]>title>
<link>http://www.infzm.com/content/91404link>
<description>description>
<category>南方周末-热点新闻category>
<author>infzmauthor>
<pubDate>2013-06-11 11:24:32pubDate>
item>
     
     
     
     
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

feedparser 最为核心的函数自然是 parse() 解析 URL 地址的函数,它返回的究竟是什么样的内容呢?

>>> feedparser.parse()
{'bozo': 1,
 'bozo_exception': xml.sax._exceptions.SAXParseException('no element found'),
 'encoding': 'utf-8',
 'entries': [],
 'feed': {},
 'namespaces': {},
 'version': ''}
     
     
     
     
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

可以看到,得到是一个字典,’feed’(key) 对应的值(value)也是一个字典,’entries’ 则是 list。

基本用法

每个 RSS 和 Atom 订阅源都包含一个标题(d.feed.title)一组文章条目(d.entries)

通常,每个文章条目都有一段摘要(d.entries[i].summary),或者是包含了条目中实际文本的描述性标签(d.entries[i].description)

>>> import feedparser
>>> d = feedparser.parse('http://blog.csdn.net/lanchunhui/rss/list')
     
     
     
     
  • 1
  • 2
  • 1
  • 2
  • (1)d.feed

    >>> d['feed']['title']                             # feed 对应一个字典
    '以数学为生,终生学习数学'
    
    >>> d.feed.title                                   # 通过属性的方式访问
    '以数学为生,终生学习数学'
    
    >>> d.feed.link
    'http://blog.csdn.net/lanchunhui'
    
    >>> d.feed.subtitle
    '数学、编程、物理、文字(The nature of reality itself)'
           
           
           
           
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • (2)d.entries

    >>> type(d.entries)
    list
    >>> len(d.entries)
    20                                                             # 共20篇文章
    
    >>> [e.title for e in e.entries][:3]
    ['[原]Spark MLlib(一)正则化特征',
     '[原]Spark 基础 —— sc.broadcast',
     '[原]Scipy 基础 —— 稀疏矩阵']
    
    >>> d.entries[0].summary             # 第一篇文章的摘要信息
    >>> d.entries[0].summary == d.entries[0].description
    True
                            # 有些条目可能会不提供 summary 信息
                            # 此时 summary 信息可通过 description 获得
           
           
           
           
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

References

[1] python feedparser 使用

原文链接:http://blog.csdn.net/lanchunhui/article/details/51020566

你可能感兴趣的:(Python)