【问题标题】:RSS feed scraping with Python使用 Python 抓取 RSS 提要
【发布时间】:2012-03-04 09:22:18
【问题描述】:

我是 Python 和一般编程的新手,所以如果问题很愚蠢,请原谅。

我一直在逐步关注this RSS 抓取教程,但在尝试收集指向正在收集的文章标题的相应链接时,我从 Python 收到“列表索引超出范围”错误。

这是我的代码:

from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import re

source  = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/raw_feed').read()

title = re.compile('<title>(.*)</title>')
link = re.compile('<link>(.*)</link>')

find_title = re.findall(title, source)
find_link = re.findall(link, source)

literate = []
literate[:] = range(1, 16)

for i in literate:
    print find_title[i]
    print find_link[i]

当我只告诉它检索标题时它执行得很好,但是当我想检索标题它们的相应链接时立即引发索引错误。

我们将不胜感激。

【问题讨论】:

    标签: python regex rss screen-scraping


    【解决方案1】:

    我认为您在从页面中提取链接时使用了错误的正则表达式。

    >>> link = re.compile('<link rel="alternate" type="text/html" href=(.*)')
    >>> find_link = re.findall(link, source)
    >>> find_link[1].strip()
    '"http://www.huffingtonpost.com/andrew-brandt/the-peyton-predicament-pa_b_1271834.html" />'
    >>> len(find_link)
    15
    >>>
    

    看一下你页面的html source你会发现链接没有括在 &lt;link&gt;&lt;/link&gt; 模式。

    其实模式是&lt;link rel="alternate" type="text/html" href= links here

    这就是你的正则表达式不起作用的原因。

    【讨论】:

      【解决方案2】:

      你可以使用feedparser module to parse an RSS feed from a given url:

      #!/usr/bin/env python
      import feedparser # pip install feedparser
      
      d = feedparser.parse('http://feeds.huffingtonpost.com/huffingtonpost/latestnews')
      # .. skipped handling http errors, cacheing ..
      
      for e in d.entries:
          print(e.title)
          print(e.link)
          print(e.description)
          print("\n") # 2 newlines
      

      输出

      Even Critics Of Safety Net Increasingly Depend On It
      http://www.huffingtonpost.com/2012/02/12/safety-net-benefits_n_1271867.html
      <p>Ki Gulbranson owns a logo apparel shop, deals in 
      <!-- ... snip ... -->
      
      Christopher Cain, Atlanta Anti-Gay Attack Suspect, Arrested And
      Charged With Aggravated Assault And Robbery
      http://www.huffingtonpost.com/2012/02/12/atlanta-anti-gay-suspect-christopher-cain-arrested_n_1271811.html
      <p>ATLANTA -- Atlanta police have arrested a suspect 
      <!-- ... snip ... -->
      

      使用regular expressions to parse rss(xml) 可能不是一个好主意。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-27
        相关资源
        最近更新 更多