1
我知道我們可以使用requests
和urllib2
包來處理重定向。我不想使用requests
,因爲它不是預建套件。請幫我用urllib2
來處理一個需要302然後移動到404的URL。我不關心404,我想跟蹤它是301還是302.Python URL重定向 - 處理302,移動到404
我提到了這個doc但它仍然拋出404
這裏是我的代碼
import urllib2
class My_HTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
my_opener = urllib2.build_opener(My_HTTPRedirectHandler)
urllib2.install_opener(my_opener)
response =urllib2.urlopen("MY URL")
print response.read()
這裏是我的迴應
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 406, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 438, in error
result = self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "<stdin>", line 3, in http_error_302
File "/usr/lib/python2.7/urllib2.py", line 625, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "/usr/lib/python2.7/urllib2.py", line 406, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 444, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found
請顯示您已經寫過的一些代碼。 – maurelio79
*「我不關心404,我想跟蹤它是301還是302。」* - [您提供的鏈接](http://www.diveintopython.net/http_web_services/redirects。 html)已經包含解決方案:['SmartRedirectHandler'](http://www.diveintopython.net/http_web_services/redirects.html#oa.redirect.2.1),使用'response.status'屬性來確定它是否是301或302重定向。 – jfs