我一直遇到一个问题,就是无法从某个网站获取RSS订阅源。我写了一个相当丑陋的程序来执行此功能,但我很好奇为什么会出现这种情况,是否有更高级别的接口可以正确处理此问题。虽然我不需要经常检索该Feed,但这个问题并不是完全可以忽略的。
我读到一种解决方案,它捕获异常并返回部分内容,但由于未完成的读取返回的字节数不同,我不能确定这种解决方案实际上是否有效。
#!/usr/bin/env python
import os
import sys
import feedparser
from mechanize import Browser
import requests
import urllib2
from httplib import IncompleteRead
url = 'http://hattiesburg.legistar.com/Feed.ashx?M=Calendar&ID=543375&GUID=83d4a09c-6b40-4300-a04b-f88884048d49&Mode=2013&Title=City+of+Hattiesburg%2c+MS+-+Calendar+(2013)'
content = feedparser.parse(url)
if 'bozo_exception' in content:
print content['bozo_exception']
else:
print "Success!!"
sys.exit(0)
print "If you see this, please tell me what happened."
# try using mechanize
b = Browser()
r = b.open(url)
try:
r.read()
except IncompleteRead, e:
print "IncompleteRead using mechanize", e
# try using urllib2
r = urllib2.urlopen(url)
try:
r.read()
except IncompleteRead, e:
print "IncompleteRead using urllib2", e
# try using requests
try:
r = requests.request('GET', url)
except IncompleteRead, e:
print "IncompleteRead using requests", e
# this function is old and I categorized it as ...
# "at least it works darnnit!", but I would really like to
# learn what's happening. Please help me put this function into
# eternal rest.
def get_rss_feed(url):
response = urllib2.urlopen(url)
read_it = True
content = ''
while read_it:
try:
content += response.read(1)
except IncompleteRead:
read_it = False
return content, response.info()
content, info = get_rss_feed(url)
feed = feedparser.parse(content)
如先前所述,这并不是一个关键任务的问题,而是一个好奇心问题。尽管我可以预料到urllib2会出现这个问题,但我对在mechanize和requests中遇到这个错误感到惊讶。feedparser模块甚至不会抛出错误,因此检查错误取决于'bozo_exception'键是否存在。
编辑:我只想提一下,无论何时wget和curl都能完美地执行该功能,正确地检索完整有效载荷。除了我的丑陋文章之外,我还没有找到纯python方法可用,并且我非常好奇httplib后台发生了什么。 几天前,我心血来潮决定也用twill尝试了一下,结果得到了相同的httplib错误。
P.S. 还有一件事情让我感到非常奇怪。 IncompleteRead在有效载荷的两个断点之一始终发生。 看起来feedparser和requests在读取926字节后失败,而mechanize和urllib2在读取1854字节后失败。 这种行为很一致,我无法解释或理解。
text/html
响应正常工作,但text/xml
不行?如果没有更全面的答案出现,您可以尝试将此问题发布到Python邮件列表中,看看是否有人能够给出诊断。 - Blair