使用Python抓取Digg RSS源

3 投票
4 回答
931 浏览
提问于 2025-04-15 22:54

有没有办法通过Digg的RSS订阅源获取链接?还是说我必须去网站上手动抓取,使用正则表达式?

我想从RSS中获取Digg指向的真实链接,而不是评论的链接。

举个例子 -

http://feeds.digg.com/~r/digg/popular/~3/Hx0VATaafSw/Apple_Scaling_Final_Cut_Studio_Apps_to_Fit_Prosumers_2

这个链接指向

http://www.appleinsider.com/articles/10/05/18/apple_scaling_final_cut_studio_apps_to_fit_prosumers.html

4 个回答

2

你可以使用Digg API中的story.getInfo方法。这个方法有一个可以用的参数叫做clean_title,你可以从RSS源中的链接提取这个参数。下面是一个示例实现:

import feedparser
import urllib2
from xml.etree import ElementTree

rss_link = 'http://feeds.digg.com/digg/popular.rss'
api_link = 'http://services.digg.com/1.0/endpoint?method=story.getInfo&clean_title=%s'

data = feedparser.parse(rss_link)

for i, e in enumerate(data.entries, 1):
  print '%d. Digg link: %s' % (i, e.link)
  title = e.link[e.link.rfind('/') + 1 :]
  xml = urllib2.urlopen(api_link % title).read()
  tree = ElementTree.fromstring(xml)
  print '%d. Real link: %s' % (i, tree.find('story').get('link'))

... 这个实现会输出:

1. Digg link: http://feeds.digg.com/~r/digg/popular/~3/V58R-d7nd2M/Pakistan_court_bans_Facebook_site
1. Real link: http://news.bbc.co.uk/2/hi/south_asia/8691406.stm
2. Digg link: http://feeds.digg.com/~r/digg/popular/~3/LoF6h1fTtk/Britons_spend_more_webtime_reading_news_than_looking_at_porn
2. Real link: http://www.telegraph.co.uk/technology/news/7740500/Britons-spend-more-web-time-reading-news-than-looking-at-pornography.html
3. Digg link: http://feeds.digg.com/~r/digg/popular/~3/XQUD2tR-qGQ/Sludgy_oil_begins_washing_into_Lousiana_s_coastal_marshes
3. Real link: http://www.washingtonpost.com/wp-dyn/content/article/2010/05/18/AR2010051801676.html?hpid=topnews
4. Digg link: http://feeds.digg.com/~r/digg/popular/~3/4HBB7lvCpoM/Professor_examines_the_complex_evolution_of_human_morality
4. Real link: http://www.physorg.com/news193472479.html
5. Digg link: http://feeds.digg.com/~r/digg/popular/~3/9__2-MVmSp4/How_Are_America_s_Top_Companies_Taxed_Infographic
5. Real link: http://www.mint.com/blog/trends/how-are-americas-top-companies-taxed/
...
3

看看这个 feedparser 模块。

>>> import feedparser
>>> d = feedparser.parse('http://feeds.digg.com/digg/popular.rss')
>>> for entry in d.entries:
...     print entry.link
...
http://feeds.digg.com/~r/digg/popular/~3/Hx0VATaafSw/Apple_Scaling_Final_Cut_Studio_Apps_to_Fit_Prosumers_2
http://feeds.digg.com/~r/digg/popular/~3/mXb8b0QH3Rc/Skateboarder_Lives_Any_Man_s_Worst_Nightmare_video
http://feeds.digg.com/~r/digg/popular/~3/61N9gFUth1k/CBS_A_bloodbath_of_cancellations
http://feeds.digg.com/~r/digg/popular/~3/vZ3_6F1RAcI/Red_Dead_Redemption_Free_Roam_Done_Right
(snip)
1

看起来你需要使用Digg的API来获取故事的真实链接,而不仅仅是Digg评论的链接。这个API可以给你提供XML或JSON格式的数据,这两种格式在Python中都很容易处理——lxmlsimplejson都很好用。

另外一个选择,如果你真的想使用RSS源的话,就是解析Digg的链接,然后从那个页面上抓取链接——不过这样效率会低一些,而且更容易出问题。

我在类似的社交新闻和博客网站上也遇到过这个问题——基本上他们希望你先访问他们的页面,然后再去阅读实际的故事。这可以理解,但从编程的角度来看,有点烦人。

撰写回答