Python 訪問網(wǎng)絡(luò)資源有很多方法,urllib, urllib2, urllib3, httplib, httplib2, requests ,現(xiàn)介紹如下兩種方法:
內(nèi)置的 urllib 模塊優(yōu)點(diǎn):自帶模塊,無需額外下載第三方庫缺點(diǎn):操作繁瑣,缺少高級功能第三方庫 requests優(yōu)點(diǎn):處理URL資源特別方便缺點(diǎn):需要下載安裝第三方庫內(nèi)置的 urllib 模塊發(fā)起GET請求主要使用urlopen()方法來發(fā)起請求,如下:
from urllib import requestresp = request.urlopen('http://xintu.baidu.com')print(resp.read().decode())訪問的結(jié)果會是一 個http.client.HTTPResponse 對象,使用此對象的 read() 方法,則可以獲取訪問網(wǎng)頁獲得的數(shù)據(jù)。但是要注意的是,獲得的數(shù)據(jù)會是 bytes 的二進(jìn)制格式,所以需要 decode() 一下,轉(zhuǎn)換成字符串格式。
發(fā)起POST請求urlopen() 默認(rèn)的訪問方式是GET,當(dāng)在 urlopen() 方法中傳入data參數(shù)時,則會發(fā)起POST請求。注意:傳遞的data數(shù)據(jù)需要為bytes格式。
設(shè)置timeout參數(shù)還可以設(shè)置超時時間,如果請求時間超出,那么就會拋出異常。如下:
from urllib import requestresp = request.urlopen('http://xintu.baidu.com', data=b'word=hello', timeout=10)print(resp.read().decode())添加Headers通過 urllib 發(fā)起的請求會有默認(rèn)的一個Headers:”User-Agent”:”Python-urllib/3.6”,指明請求是由 urllib 發(fā)送的。所以遇到一些驗(yàn)證User-Agent的網(wǎng)站時,我們需要自定義Headers,而這需要借助于urllib.request中的 Request 對象。
from urllib import requesturl = 'http://httpbin.org/get'headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'}# 需要使用url和headers生成一個Request對象,然后將其傳入urlopen方法中req = request.Request(url, headers=headers)resp = request.urlopen(req)print(resp.read().decode())Request對象如上所示, urlopen() 方法中不止可以傳入字符串格式的url,也可以傳入一個 Request 對象來擴(kuò)展功能,Request 對象如下:
class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)構(gòu)造 Request 對象必須傳入url參數(shù),data數(shù)據(jù)和headers都是可選的。
最后, Request 方法可以使用method參數(shù)來自由選擇請求的方法,如PUT,DELETE等等,默認(rèn)為GET。
添加Cookie為了在請求時能帶上Cookie信息,我們需要重新構(gòu)造一個opener。
使用request.build_opener方法來進(jìn)行構(gòu)造opener,將我們想要傳遞的cookie配置到opener中,然后使用這個opener的open方法來發(fā)起請求。如下:
from http import cookiejarfrom urllib import requesturl = 'https://xintu.baidu.com'# 創(chuàng)建一個cookiejar對象cookie = cookiejar.CookieJar()# 使用HTTPCookieProcessor創(chuàng)建cookie處理器cookies = request.HTTPCookieProcessor(cookie)# 并以它為參數(shù)創(chuàng)建Opener對象opener = request.build_opener(cookies)# 使用這個opener來發(fā)起請求resp = opener.open(url)# 查看之前的cookie對象,則可以看到訪問百度獲得的cookiefor i in cookie: print(i)或者也可以把這個生成的opener使用install_opener方法來設(shè)置為全局的。
則之后使用urlopen方法發(fā)起請求時,都會帶上這個cookie。
# 將這個opener設(shè)置為全局的openerrequest.install_opener(opener)resp = request.urlopen(url)設(shè)置Proxy代理使用爬蟲來爬取數(shù)據(jù)的時候,常常需要使用代理來隱藏我們的真實(shí)IP。如下:
from urllib import requesturl = 'http://xintu.baidu.com'proxy = {'http':'222.222.222.222:80','https':'222.222.222.222:80'}# 創(chuàng)建代理處理器proxies = request.ProxyHandler(proxy)# 創(chuàng)建opener對象opener = request.build_opener(proxies)resp = opener.open(url)print(resp.read().decode())下載數(shù)據(jù)到本地在我們進(jìn)行網(wǎng)絡(luò)請求時常常需要保存圖片或音頻等數(shù)據(jù)到本地,一種方法是使用python的文件操作,將read()獲取的數(shù)據(jù)保存到文件中。
而urllib提供了一個urlretrieve()方法,可以簡單地直接將請求獲取的數(shù)據(jù)保存成文件。如下:
from urllib import requesturl = 'http://python.org/'request.urlretrieve(url, 'python.html')urlretrieve() 方法傳入的第二個參數(shù)為文件保存的位置,以及文件名。
注意:urlretrieve() 方法是python2直接移植過來的方法,以后有可能在某個版本中棄用。
第三方庫 requests安裝由于 requests是第三方庫,所以要先安裝,如下:
pip install requests發(fā)起GET請求直接用 get 方法,如下:
import requestsr = requests.get('http://xintu.baidu.com/')print(r.status_code) #狀態(tài)print(r.text) #內(nèi)容對于帶參數(shù)的URL,傳入一個dict作為params參數(shù),如下:
import requestsr = requests.get('http://xintu.baidu.com/', params={'q': 'python', 'cat': '1001'})print(r.url) #實(shí)際請求的URLprint(r.text)requests的方便之處還在于,對于特定類型的響應(yīng),例如JSON,可以直接獲取,如下:
r = requests.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json')r.json()# {'query': {'count': 1, 'created': '2017-11-17T07:14:12Z', ...添加Headers需要傳入HTTP Header時,我們傳入一個dict作為headers參數(shù),如下:添加Headers需要傳入HTTP Header時,我們傳入一個dict作為headers參數(shù),如下:
r = requests.get('https://xintu.baidu.com/', headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit'})獲取響應(yīng)頭,如下:
r.headers# {Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Content-Encoding': 'gzip', ...}r.headers['Content-Type']# 'text/html; charset=utf-8'發(fā)起POST請求要發(fā)送POST請求,只需要把get()方法變成post(),然后傳入data參數(shù)作為POST請求的數(shù)據(jù),如下:
r = requests.post('https://accounts.baidu.com/login', data={'form_email': 'abc@example.com', 'form_password': '123456'})requests默認(rèn)使用application/x-xintu-form-urlencoded對POST數(shù)據(jù)編碼。如果要傳遞JSON數(shù)據(jù),可以直接傳入json參數(shù),如下:
params = {'key': 'value'}r = requests.post(url, json=params) #內(nèi)部自動序列化為JSON上傳文件上傳文件需要更復(fù)雜的編碼格式,但是requests把它簡化成files參數(shù),如下:
upload_files = {'file': open('report.xls', 'rb')}r = requests.post(url, files=upload_files)在讀取文件時,注意務(wù)必使用 'rb' 即二進(jìn)制模式讀取,這樣獲取的 bytes 長度才是文件的長度。
把 post() 方法替換為 put() , delete() 等,就可以以PUT或DELETE方式請求資源。
添加Cookie在請求中傳入Cookie,只需準(zhǔn)備一個dict傳入cookies參數(shù),如下:
cs = {'token': '12345', 'status': 'working'}r = requests.get(url, cookies=cs)requests對Cookie做了特殊處理,使得我們不必解析Cookie就可以輕松獲取指定的Cookie,如下:
r.cookies['token']# 12345指定超時要指定超時,傳入以秒為單位的timeout參數(shù)。超時分為連接超時和讀取超時,如下:
try: # 3.1秒后連接超時,27秒后讀取超時 r = requests.get(url, timeout=(3.1, 27))except requests.exceptions.RequestException as e: print(e)超時重連def gethtml(url): i = 0 while i < 3: try: html = requests.get(url, timeout=5).text return html except requests.exceptions.RequestException: i += 1添加代理同添加headers方法,代理參數(shù)也要是一個dict,如下:
heads = { 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit'}proxy = { 'http': 'http://120.25.253.234:812', 'https' 'https://163.125.222.244:8123'}r = requests.get('https://xintu.baidu.com/', headers=heads, proxies=proxy)掃描二維碼推送至手機(jī)訪問。
版權(quán)聲明:本文由信途科技轉(zhuǎn)載于網(wǎng)絡(luò),如有侵權(quán)聯(lián)系站長刪除。
轉(zhuǎn)載請注明出處https://1.13.168.162/xintu/9022.html