Python:Urllib2 返回 404

1 投票
2 回答
592 浏览
提问于 2025-04-17 23:36

我正在尝试用Python从一个网址读取一些内容,但每次都遇到404错误。

这是我的测试代码和出问题的网址:

url = 'http://supercoach.heraldsun.com.au'

headers = {"User-agent": "Mozilla/5.0"}
req = urllib2.Request(url, None, headers)
try:
   handle = urllib2.urlopen(req)
except IOError, e:
    print e.code

这个网站在浏览器中运行得很好,我之前用这个脚本也没有问题,但最近网站更新后就出错了。

我试着添加了一个用户代理头,因为类似的问题中有人建议这么做。

有没有人知道为什么这不管用呢?

谢谢,JP

2 个回答

1

试着设置一下 cookies,并增加允许的重定向次数:

import urllib2
from cookielib import CookieJar

class RedirectHandler(urllib2.HTTPRedirectHandler):
    max_repeats = 100
    max_redirections = 1000

    def http_error_302(self, req, fp, code, msg, headers):
        print code
        print headers
        return urllib2.HTTPRedirectHandler.http_error_302(
            self, req, fp, code, msg, headers)
    http_error_300 = http_error_302
    http_error_301 = http_error_302
    http_error_303 = http_error_302
    http_error_307 = http_error_302

cookiejar = CookieJar()
urlopen = urllib2.build_opener(RedirectHandler(),
                               urllib2.HTTPCookieProcessor(cookiejar)).open
request = urllib2.Request('http://supercoach.heraldsun.com.au',
                          headers={"User-agent": "Mozilla/5.0"})
response = urlopen(request)
print '*' * 60
print response.info()
print response.read()
response.close()
1

使用 requests 这个库,它为 Python 中的其他库提供了一个简单易用的封装;而且它会为你 处理重定向

用 requests 写的代码非常简单:

import requests
r = requests.get('http://supercoach.heraldsun.com.au')

撰写回答