Python中使用urllib2防止302跳轉的代碼例子
更新時間:2014年07月07日 10:48:24 投稿:junjie
這篇文章主要介紹了Python中使用urllib2防止302跳轉的代碼例子,即避免302跳轉的實現(xiàn),需要的朋友可以參考下
說明:python的urllib2獲取網(wǎng)頁(urlopen)會自動重定向(301,302)。但是,有時候我們需要獲取302,301頁面的狀態(tài)信息。就必須獲取到轉向前的調試信息。
下面代碼將可以做到避免302重定向到新的網(wǎng)頁
#!/usr/bin/python
# -*- coding: utf-8 -*-
#encoding=utf-8
#Filename:states_code.py
import urllib2
class RedirctHandler(urllib2.HTTPRedirectHandler):
"""docstring for RedirctHandler"""
def http_error_301(self, req, fp, code, msg, headers):
pass
def http_error_302(self, req, fp, code, msg, headers):
pass
def getUnRedirectUrl(url,timeout=10):
req = urllib2.Request(url)
debug_handler = urllib2.HTTPHandler(debuglevel = 1)
opener = urllib2.build_opener(debug_handler, RedirctHandler)
html = None
response = None
try:
response = opener.open(url,timeout=timeout)
html = response.read()
except urllib2.URLError as e:
if hasattr(e, 'code'):
error_info = e.code
elif hasattr(e, 'reason'):
error_info = e.reason
finally:
if response:
response.close()
if html:
return html
else:
return error_info
html = getUnRedirectUrl('http://jb51.net')
print html
您可能感興趣的文章:
相關文章
Python tensorflow與pytorch的浮點運算數(shù)如何計算
這篇文章主要介紹了Python tensorflow與pytorch的浮點運算數(shù)如何計算,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2022-11-11
如何安裝并使用conda指令管理python環(huán)境
這篇文章主要介紹了如何使用conda指令管理python環(huán)境,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-07-07
python3 實現(xiàn)爬取TOP500的音樂信息并存儲到mongoDB數(shù)據(jù)庫中
今天小編就為大家分享一篇python3 實現(xiàn)爬取TOP500的音樂信息并存儲到mongoDB數(shù)據(jù)庫中,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
利用Python實現(xiàn)讀取Word文檔里的Excel附件
這篇文章主要為大家詳細介紹了如何利用Python實現(xiàn)讀取Word文檔里的Excel附件,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下2022-12-12

