Python爬蟲之requests庫基本介紹
一、說明
requests是一個很實用的Python HTTP客戶端庫,爬蟲和測試服務(wù)器響應(yīng)數(shù)據(jù)時經(jīng)常會用到,requests是Python語言的第三方的庫,專門用于發(fā)送HTTP請求,使用起來比urllib簡潔很多。
Requests 有這些功能:
1、Keep-Alive & 連接池
2、國際化域名和 URL
3、帶持久 Cookie 的會話
4、瀏覽器式的 SSL 認(rèn)證
5、自動內(nèi)容解碼
6、基本/摘要式的身份認(rèn)證
7、優(yōu)雅的 key/value Cookie
8、自動解壓
9、Unicode 響應(yīng)體
10、HTTP(S) 代理支持
11、文件分塊上傳
12、流下載
13、連接超時
14、分塊請求
15、支持 .netrc
Requests 支持 Python 2.6—2.7以及3.3—3.7,而且能在 PyPy 下完美運行。
用pip進(jìn)行第三方庫的安裝
pip install requests
安裝完成后import一下,正常則說明可以開始使用了。
二、基本用法:
1、requests.get()
用于請求目標(biāo)網(wǎng)站,類型是一個HTTPresponse類型
import requests response = requests.get('http://www.baidu.com') print(response.status_code) # 打印狀態(tài)碼 print(response.url) # 打印請求url print(response.headers) # 打印頭信息 print(response.cookies) # 打印cookie信息 print(response.text) #以文本形式打印網(wǎng)頁源碼 print(response.content) #以字節(jié)流形式打印 print(response.content.decode("utf-8")) #解決了通過response.text直接返回顯示亂碼的問題 response.encoding="utf-8" #避免亂碼的問題發(fā)生
2、各種請求方式
import requests requests.get('http://httpbin.org/get') requests.post('http://httpbin.org/post') requests.put('http://httpbin.org/put') requests.delete('http://httpbin.org/delete') requests.head('http://httpbin.org/get') requests.options('http://httpbin.org/get')
3、基本的get請求
import requests response = requests.get('http://httpbin.org/get') print(response.text)
4、帶參數(shù)的get請求
第一種直接將參數(shù)放在url內(nèi)
import requests response = requests.get(http://httpbin.org/get?name=gemey&age=22) print(response.text)
另一種先將參數(shù)填寫在dict中,發(fā)起請求時params參數(shù)指定為dict
import requests data = { 'name': 'tom', 'age': 20 } response = requests.get('http://httpbin.org/get', params=data) print(response.text)
5、解析json
import requests response = requests.get('http://httpbin.org/get') print(response.text) print(response.json()) #response.json()方法同json.loads(response.text) print(type(response.json()))
如果 JSON 解碼失敗, 將會拋出 ValueError: No JSON object could be decoded 異常。而成功調(diào)用 response.json() 并不意味著響應(yīng)的成功。有的服務(wù)器會在失敗的響應(yīng)中包含一個 JSON 對象(比如 HTTP 500 的錯誤細(xì)節(jié))。這種 JSON 會被解碼返回。要檢查請求是否成功,請使用 r.raise_for_status() 或者檢查 response.status_code 是否和你的期望相同
6、保存一個二進(jìn)制文件
二進(jìn)制內(nèi)容為response.content
import requests response = requests.get('http://img.ivsky.com/img/tupian/pre/201708/30/kekeersitao-002.jpg') b = response.content with open('F://fengjing.jpg','wb') as f: f.write(b)
7、添加heads信息
import requests heads = {} heads['User-Agent'] = 'Mozilla/5.0 ' \ '(Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 ' \ '(KHTML, like Gecko) Version/5.1 Safari/534.50' response = requests.get('http://www.baidu.com',headers=headers)
8、使用代理
同添加headers方法,代理參數(shù)也要是一個dict
這里使用requests庫爬取了IP代理網(wǎng)站的IP與端口和類型
import requests import re def get_html(url): proxy = { 'http': '120.25.253.234:812', 'https': '163.125.222.244:8123' } heads = {} heads['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0' req = requests.get(url, headers=heads,proxies=proxy) html = req.text return html def get_ipport(html): regex = r'<td data-title="IP">(.+)</td>' iplist = re.findall(regex, html) regex2 = '<td data-title="PORT">(.+)</td>' portlist = re.findall(regex2, html) regex3 = r'<td data-title="類型">(.+)</td>' typelist = re.findall(regex3, html) sumray = [] for i in iplist: for p in portlist: for t in typelist: pass pass a = t+','+i + ':' + p sumray.append(a) print('高匿代理') print(sumray) if __name__ == '__main__': url = 'http://www.kuaidaili.com/free/' get_ipport(get_html(url))
9、基本POST請求
import requests data = {'name':'tom','age':'22'} response = requests.post('http://httpbin.org/post', data=data)
10、獲取cookie
import requests response = requests.get('http://www.baidu.com') print(response.cookies) print(type(response.cookies)) for k,v in response.cookies.items(): print(k+':'+v)
11、會話維持
import requests session = requests.Session() session.get('http://httpbin.org/cookies/set/number/12345') response = session.get('http://httpbin.org/cookies') print(response.text)
11、證書驗證設(shè)置
import requests from requests.packages import urllib3 urllib3.disable_warnings() #從urllib3中消除警告 response = requests.get('https://www.12306.cn',verify=False) #證書驗證設(shè)為FALSE print(response.status_code)
12、超時異常捕獲
import requests from requests.exceptions import ReadTimeout try: res = requests.get('http://httpbin.org', timeout=0.1) print(res.status_code) except ReadTimeout: print(timeout)
13、異常處理
在你不確定會發(fā)生什么錯誤時,盡量使用try…except來捕獲異常
import requests from requests.exceptions import ReadTimeout,HTTPError,RequestException try: response = requests.get('http://www.baidu.com',timeout=0.5) print(response.status_code) except ReadTimeout: print('timeout') except HTTPError: print('httperror') except RequestException: print('reqerror')
總結(jié)
到此這篇關(guān)于Python爬蟲之requests庫基本介紹的文章就介紹到這了,更多相關(guān)Python requests庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Python實現(xiàn)簡單的漢字拼音轉(zhuǎn)換工具
將漢字轉(zhuǎn)為拼音,可以用于批量漢字注音、文字排序、拼音檢索文字等常見場景?,F(xiàn)在互聯(lián)網(wǎng)上有許多拼音轉(zhuǎn)換工具,基于Python的開源模塊也不少,本文將利用pypinyin模塊制作簡單的漢字拼音轉(zhuǎn)換工具,感興趣的可以了解一下2022-09-09Python+Pygame實現(xiàn)之走四棋兒游戲的實現(xiàn)
大家以前應(yīng)該都聽說過一個游戲:叫做走四棋兒。直接在家里的水泥地上用燒完的炭火灰畫出幾條線,擺上幾顆石頭子即可。當(dāng)時的火爆程度可謂是達(dá)到了一個新的高度。本文將利用Pygame實現(xiàn)這一游戲,需要的可以參考一下2022-07-07MacOS(M1芯片 arm架構(gòu))下安裝PyTorch的詳細(xì)過程
這篇文章主要介紹了MacOS(M1芯片 arm架構(gòu))下安裝PyTorch的詳細(xì)過程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02Win10系統(tǒng)下Pytorch環(huán)境的搭建過程
今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識,文章圍繞著Win10系統(tǒng)Pytorch環(huán)境搭建過程展開,文中有非常詳細(xì)的介紹及圖文示例,需要的朋友可以參考下2021-06-06Python實現(xiàn)獲取當(dāng)前目錄下文件名代碼詳解
這篇文章主要介紹了Python實現(xiàn)獲取當(dāng)前目錄下文件名,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03如何在Python中導(dǎo)入EXCEL數(shù)據(jù)
這篇文章主要介紹了使用Python處理EXCEL基礎(chǔ)操作篇1,如何在Python中導(dǎo)入EXCEL數(shù)據(jù),文中提供了解決思路和部分實現(xiàn)代碼,一起來看看吧2023-03-03pytorch快速搭建神經(jīng)網(wǎng)絡(luò)_Sequential操作
這篇文章主要介紹了pytorch快速搭建神經(jīng)網(wǎng)絡(luò)_Sequential操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06