urllib2模塊是Python標準庫中處理HTTP請求的基本工具之一。它支持重定向、cookie、代理等常規功能,同時可以擴展實現更靈活的請求。本文將從多個角度詳細介紹urllib2模塊的使用。
一、urlopen函數
urlopen函數是urllib2模塊最基本的函數,它可以用來打開URL鏈接。下面是一個使用urlopen函數獲取網頁內容的代碼示例:
import urllib2 response = urllib2.urlopen('https://www.baidu.com/') html = response.read() print html
其中,urlopen方法接收一個網址URL參數,返回的是一個HTTPResponse對象。我們可以使用read方法讀取到網頁的源代碼。
另外,在Python2.x版本中,urlopen方法還可以傳入data參數,作為請求的數據。例如:
import urllib2 import urllib data = {'username': 'test', 'password': '123'} data = urllib.urlencode(data) # 將字典類型的數據轉為URL編碼的字元串 url = 'http://www.example.com/login' req = urllib2.Request(url, data) response = urllib2.urlopen(req) result = response.read() print result
其中,通過urllib.urlencode方法將data轉為URL編碼字元串,並通過urllib2.Request構造Request對象,最後傳入urlopen函數即可。
二、urllib庫
urllib與urllib2是Python標準庫中的兩個HTTP客戶端工具庫,常見任務包括發送請求,處理響應數據等。下面介紹一些常用的urllib庫相關操作。
1. urlretrieve方法
urlretrieve方法可以將遠程數據下載到本地。下面是一段例子:
import urllib url = 'http://www.example.com/example.jpg' urllib.urlretrieve(url, 'example.jpg')
其中,urllib.urlretrieve(url, filename=None, reporthook=None, data=None)方法接收四個參數:遠程資源URL鏈接,保存本地文件的文件名,下載進度反饋函數,post提交的數據等。
2. urlencode方法
urlencode方法可以將字典類型的數據轉為URL編碼的字元串。下面是一個例子:
import urllib data = {'name': 'test', 'age': 20} data = urllib.urlencode(data) print data
運行結果為:name=test&age=20
3. quote/ unquote方法
quote/ unquote方法可以將字元串進行URL編碼和解碼。例如:
import urllib str1 = 'hello world' str_encode = urllib.quote(str1) print str_encode str_decode = urllib.unquote(str_encode) print str_decode
運行結果分別為:hello%20world和hello world
三、其他功能
1. 設置請求頭
在請求中加入headers參數,可以用來設置請求頭。
import urllib2 url = 'http://www.example.com' headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'} req=urllib2.Request(url, headers=headers) response = urllib2.urlopen(req) html = response.read() print html
2. 設置代理
可以使用urllib2中的ProxyHandler類來設置代理。下面是一個例子:
import urllib2 proxy_support = urllib2.ProxyHandler({'http': 'http://username:password@proxy_address:port'}) opener = urllib2.build_opener(proxy_support) urllib2.install_opener(opener) response = urllib2.urlopen('http://www.example.com') html = response.read() print html
3. 處理Cookie
urllib2同時支持處理Cookie。下面是一個例子:
import urllib2 import cookielib cookie = cookielib.CookieJar() handler = urllib2.HTTPCookieProcessor(cookie) opener = urllib2.build_opener(handler) response = opener.open('http://www.example.com') for item in cookie: print '%s=%s' % (item.name, item.value)
這裡我們先創建一個CookieJar的實例,然後通過HTTPCookieProcessor(handler)創建一個處理器對象handler,最後創建一個Opener對象opener並且安裝處理器。這樣我們就可以發送請求並且處理Cookie了。
本文介紹了urilib2模塊的基本操作以及urllib庫的常用方法。通過上述內容的學習,希望讀者可以更加深入地了解Python中的HTTP請求操作。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/295759.html