使用 Python/urllib2 处理 rss 重定向 [英] Handling rss redirects with Python/urllib2

查看:50
本文介绍了使用 Python/urllib2 处理 rss 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在指向从 RSS 提要获取的文章的链接上调用 urrlib2.urlopen 会导致以下错误:

Calling urrlib2.urlopen on a link to an article fetched from an RSS feed leads to the following error:

urllib2.HTTPError:HTTP 错误 301:HTTP 服务器返回重定向会导致无限循环的错误.最后的 30x 错误消息是:永久移动

urllib2.HTTPError: HTTP Error 301: The HTTP server returned a redirect error tha t would lead to an infinite loop. The last 30x error message was: Moved Permanently

根据文档,urllib2 支持重定向.

According to the documentation, urllib2 supports redirects.

在 Java 上,只需调用即可解决问题

On Java the problem was solved by just calling

HttpURLConnection.setFollowRedirects(true);

如何用 Python 解决?

How can I solve it with Python?

更新

我遇到问题的链接:

http://feeds.nytimes.com/click.phdo?i=8cd5af579b320b0bfd3469/a>

http://feeds.nytimes.com/click.phdo?i=8cd5af579b320b0bfd695ddcc344d96c

推荐答案

事实证明您需要启用 Cookie.页面在首先设置 cookie 后重定向到自身.因为 urllib2 默认不处理 cookie,所以你必须自己做.

Turns out you need to enable Cookies. The page redirects to itself after setting a cookie first. Because urllib2 does not handle cookies by default you have to do it yourself.

import urllib2
import urllib
from cookielib import CookieJar

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
p = opener.open("http://feeds.nytimes.com/click.phdo?i=8cd5af579b320b0bfd695ddcc344d96c")

print p.read()

这篇关于使用 Python/urllib2 处理 rss 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆