python解析排名最靠前的5条新闻

!/usr/bin/env python

try:
from io import BytesIO as StringIO
except ImportError:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO

try:
from itertools import izip as zip
except ImportError:
pass

try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen

from pprint import pprint
from xml.etree import ElementTree

g = urlopen('http://news.google.com/news?topic=h&output=rss')
f = StringIO(g.read())
g.close()
tree = ElementTree.parse(f)
f.close()

def topnews(count=5):
pair = [None, None]
for elmt in tree.getiterator():
if elmt.tag == 'title':
skip = elmt.text.startswith('Top Stories')
if skip:
continue
pair[0] = elmt.text
if elmt.tag == 'link':
if skip:
continue
pair[1] = elmt.text
if pair[0] and pair[1]:
count -= 1
yield(tuple(pair))
if not count:
return
pair = [None, None]

for news in topnews():
pprint(news)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,554评论 0 13
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,456评论 3 20
  • 不知有多久 我没像今晚这样 与我的父母同睡在一个房间 我想,大概有十五年了吧 唯一的枕头 让给了我 我现在枕着的 ...
    多糖阅读 235评论 2 3
  • 夜市的繁华, 游戏的打闹, 不确定的自信和迈不快的脚步 也许成了你和我之间的另一道屏障 ​​​
    辰心范阅读 291评论 0 0