python中使用urllib2防止302跳轉的代碼例子
來源:易賢網 閱讀:1180 次 日期:2016-06-14 10:21:42
溫馨提示:易賢網小編為您整理了“python中使用urllib2防止302跳轉的代碼例子”,方便廣大網友查閱!

這篇文章主要介紹了python中使用urllib2防止302跳轉的代碼例子,即避免302跳轉的實現,需要的朋友可以參考下。

說明:python的urllib2獲取網頁(urlopen)會自動重定向(301,302)。但是,有時候我們需要獲取302,301頁面的狀態信息。就必須獲取到轉向前的調試信息。

下面代碼將可以做到避免302重定向到新的網頁

#!/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

更多信息請查看腳本欄目
由于各方面情況的不斷調整與變化,易賢網提供的所有考試信息和咨詢回復僅供參考,敬請考生以權威部門公布的正式信息和咨詢為準!

2026國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機號
  • 驗證碼
關于我們 | 聯系我們 | 人才招聘 | 網站聲明 | 網站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
工業和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
云南網警備案專用圖標
聯系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關注公眾號:hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權所有:易賢網
云南網警報警專用圖標
未满十八18勿进黄网站免费看