歡迎您光臨本站 註冊首頁

Python urllib2運行過程原理解析

←手機掃碼閱讀     zhang3221994 @ 2020-06-08 , reply:0

1.urlopen函數
 

urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])
 

注:
 

url表示目標網頁地址,可以是字符串,也可以是請求對象Request
 

req= urllib2.Request(url, data,headers) response = urllib2.urlopen(req,timeout=3)
 

data表示post方式提交給目標服務器的參數
 

data = urllib.urlencode(data)

  import urllib,urllib2   action_url="http://www.xxxxxx.com/post"#用於測試post的網址,返回提交的數據   values={'name':"alice",'age':20}   data=urllib.urlencode(values)#對錶單數據編碼   rqst=urllib2.Request(action_url,data)   response=urllib2.urlopen(rqst)#模擬提交表單數據到url並獲得響應

 

timeout表示超時時間設置。
 

返回值
 

  • response.read()返回頁面內容

  • response.info()返回網頁信息

  • response.geturl()返回連接地址

這個函數可以像urllib.urlopen()那樣以url做參數。也能以Request實例為參數,即用一個Request對象(下文構造方法)來映射你提出的HTTP請求,在它最簡單的使用形式中你將用你要請求的地址創建一個Request對象,這個Request對象中可以設置傳輸數據、headers等。通過調用urlopen並傳入Request對象,將返回一個file-like對象。urllib2還提供了接口來處理一般情況,例如:基礎驗證,cookies,代理和其他,它們通過handlers和openers的對象實現。
 

2、Request函數
 

urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])
 

用於構造Request對象,可以傳遞data數據,添加請求頭(headers)等,構造好後作為urllib2.urlopen()的參數。
 

注:
 

url表示目標網頁地址,可以是字符串,也可以是請求對象Request
 

data表示post方式提交給目標服務器的參數
 

headers表示用戶標識,是一個字典類型的數據,有些不允許腳本的抓取,所以需要用戶代理,像火狐瀏覽器的代理就是類似:

Mozilla/5.0 (X11; U; Linux i686)Gecko/20071127 Firefox/2.0.0.11
 

瀏覽器的標準UA格式為:瀏覽器標識 (操作系統標識; 加密等級標識; 瀏覽器語言) 渲染引擎標識 版本信息 ,headers默認是

Python-urllib/2.6
 

origin_req_host表示請求方的主機域名或者ip地址。

headers = {'User-Agent':'Mozilla/5.0 (X11; U; Linux i686)Gecko/20071127 Firefox/2.0.0.11'}

  import urllib    import urllib2    url = 'http://www.weibo.cn/'    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'    h = { 'User-Agent' : user_agent }    req = urllib2.Request(url,headers=h)    response = urllib2.urlopen(req)    print response.read()

 

3、build_opener()
 

build_opener([handler1 [ handler2, ... ]])

urllib2.urlopen()函數不支持驗證、cookie或者其它HTTP高級功能。要支持這些功能,必須使用build_opener()函數創建自定義Opener對象。
 

參數handler是Handler實例,常用的有HTTPBasicAuthHandler、HTTPCookieProcessor、ProxyHandler等。
 build_opener ()返回的對象具有open()方法,與urlopen()函數的功能相同。
 

如果要修改http報頭,可以用:

  import urllib2   opener = urllib2.build_opener()   opener.addheaders = [('User-agent', 'Mozilla/5.0')]   opener.open('http://www.example.com/')

  


[zhang3221994 ] Python urllib2運行過程原理解析已經有213次圍觀

http://coctec.com/docs/python/shhow-post-237516.html