python requests模塊的使用示例
為什么使用requests:
- 支持使用Cookie保持會(huì)話
- 支持文件上傳
- 支持自動(dòng)確定響應(yīng)內(nèi)容的編碼
- 對(duì)用戶來(lái)說(shuō)比較人性化
模擬get請(qǐng)求:
獲取token
# 使用微信公眾平臺(tái)舉例 get_param_dict={ "grant_type":"**************", "appid":"**************", "secret":"**************", } response = requests.get(url='https://api.weixin.qq.com/cgi-bin/token', # url地址 params=get_param_dict) # 參數(shù) print(response.content.decode('utf-8'))
模擬請(qǐng)求頭部信息
注:因?yàn)閞equests請(qǐng)求頭是以python,requests發(fā)起的,所以大部分接口都會(huì)需要手動(dòng)添加頭部信息
# get 模擬請(qǐng)求頭部信息,(當(dāng)你發(fā)現(xiàn)數(shù)據(jù)不對(duì)時(shí),就模擬) # 以百度舉例 get_param_dict ={ "wd":"newdream" } # 添加頭部信息字典(可以使用抓包抓取到頭部信息) header_info_dict = { "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36", "Accpet":"text/plain, */*; q=0.01" } response = requests.get(url = 'https://www.baidu.com/s', params=get_param_dict,headers=header_info_dict) print(response.content.decode('utf-8'))
模擬post請(qǐng)求
import requests,json # requests模擬發(fā)送post請(qǐng)求 # 使用微信公眾平臺(tái)舉例 url_param_doct = {"access_token": "43_XcK_1rvR8VPgicGGzq7Vp2QrGx30Kwhy9SSShoVTQs11G_jP9aqhy2bwRQFuG2hYzkwVjphJFfPj8WYQR8vgfu5Xej7KaZBiyPDJ9sYoCKte78sqgtBdCf6N5S8QosNXBOFSEJnzLMbxJwCOTWAgAAANQU"} post_param_data = { "tag" : { "name" : "我是新標(biāo)簽" } } response = requests.post(url='https://api.weixin.qq.com/cgi-bin/tags/create', params=url_param_doct, # json=post_param_data # 可以使用json data=json.dumps(post_param_data) # 也可以使用data,但是data要求是字符串,需要使用json模塊dumps轉(zhuǎn)化 ) print(response.content.decode('utf-8'))
requests上傳文件
import requests,os # post上傳文件 current_path = os.path.dirname(__file__) # os模塊定位當(dāng)前路徑 excel_path = os.path.join(current_path,'..','data','j.xlsx') # join拼接 excel_file = {'file':open(excel_path,'rb')} # 做成字典,open打開(kāi)文件 rb:只讀二進(jìn)制 response = requests.post(url='https://2.python-requests.org/', # requests官方實(shí)例文檔地址 files=excel_file) # files傳文件 print( response.content.decode('utf-8') )
requests設(shè)置代理
import requests # 設(shè)置代理:為什么設(shè)置代理? # 爬蟲(chóng)類(lèi)項(xiàng)目,有檢測(cè)機(jī)制 # 防止公司系統(tǒng)有防灌水功能 # 需要翻墻做接口的時(shí)候 proxy_server = {'http':'http://127.0.0.1:8888', 'https':'http://127.0.0.1:8888'} # 做一個(gè)字典 proxy_user_pass = { 'https':'http://uesrname:password@127.0.0.1:8888' # 需要用戶跟密碼使用這個(gè) } response = requests.get(url= 'https://baidu.com', proxies=proxy_server) # proxies設(shè)置代理關(guān)鍵字 print(response.status_code)
time模塊設(shè)置請(qǐng)求超時(shí)
如果一個(gè)請(qǐng)求很久沒(méi)有結(jié)果,就會(huì)讓整個(gè)項(xiàng)目的效率變得非常低,這個(gè)時(shí)候我們就需要對(duì)請(qǐng)求進(jìn)行強(qiáng)制要求
讓他必須在特定的時(shí)間內(nèi)返回結(jié)果,否則就報(bào)錯(cuò)。
# 設(shè)置請(qǐng)求超時(shí) import requests import time print(time.time()) # 時(shí)間戳 response = requests.get(url='https://www.baidu.com',timeout=3) # timeout=3: 請(qǐng)求如果在規(guī)定時(shí)間之內(nèi)(3秒鐘內(nèi))沒(méi)有得到響應(yīng),就會(huì)拋出超時(shí)錯(cuò)誤 print(time.time())
retrying模塊設(shè)置刷新
使用超時(shí)參數(shù)能夠加快我們整體的請(qǐng)求速度,但是在正常的網(wǎng)頁(yè)瀏覽過(guò)成功,如果發(fā)生速度很慢的情況,我們會(huì)做的選擇是刷新頁(yè)面
retrying模塊就可以幫助我們解決。使用retrying模塊提供的retry模塊
通過(guò)裝飾器的方式使用,讓被裝飾的函數(shù)反復(fù)執(zhí)行retry中可以傳入?yún)?shù)stop_max_attempt_number,讓函數(shù)報(bào)錯(cuò)后繼續(xù)重新執(zhí)行
達(dá)到最大執(zhí)行次數(shù)的上限,如果每次都報(bào)錯(cuò),整個(gè)函數(shù)報(bào)錯(cuò),如果中間有一個(gè)成功,程序繼續(xù)往后執(zhí)行。
import requests from retrying import retry # 如果函數(shù)連續(xù)調(diào)用三次都報(bào)錯(cuò),才會(huì)報(bào)錯(cuò),如果三次之中有一次成功,就成功 @retry(stop_max_attempt_number=3) def get_response(url): response = requests.get(url, timeout=2) return response retrying_requests = get_response("https://www.baidu.com") print(retrying_requests.content.decode())
cookie設(shè)置
好處:能夠訪問(wèn)登錄后的頁(yè)面
壞處:一套cookie往往對(duì)應(yīng)的是一個(gè)用戶的信息,請(qǐng)求太頻繁有更大的可能性被對(duì)方識(shí)別為爬蟲(chóng)
如何解決 ?使用多個(gè)賬號(hào)
# 使用requests提供的session模塊 import requests # 構(gòu)造formdata表單數(shù)據(jù),填寫(xiě)自己的賬號(hào)和密碼 post_data = { "username": "xxxxx", "password": "xxxxx" } # session的使用: 在請(qǐng)求之前創(chuàng)建session對(duì)象 session = requests.Session() # 后續(xù)的請(qǐng)求都由session來(lái)發(fā)起,因?yàn)閟ession中保存了用戶的登陸信息 session.post(url="https://www.baidu.com", data=post_data) response = session.get("https://www.baidu.com") # 使用session請(qǐng)求登陸后的界面 print(response.content.decode())
處理證書(shū)認(rèn)證錯(cuò)誤
import requests # 方式一:不驗(yàn)證證書(shū),報(bào)警告,返回200 requests.packages.urllib3.disable_warnings()# 直接解決爆紅警告 # 方式二不驗(yàn)證證書(shū),報(bào)警告,返回200 ,后面拼接verify=False,加這個(gè)控制臺(tái)報(bào)警的話,就在加上方式一 response = requests.get('https://www.12306.cn',verify=False) print(response.content.decode('utf-8')) # 方式三:安裝pyopenssl 安裝之后就不會(huì)報(bào)錯(cuò)# pip3 install -U requests[security] response = requests.get('https://www.12306.cn') print(response.content.decode('utf-8')) # 方式四: 加上證書(shū) 公司內(nèi)部 問(wèn)開(kāi)發(fā)要xxx.crt文件 ,最穩(wěn)妥 response = requests.get('https://www.12306.cn',cert=('/path/server.crt', '/path/key'))
requests+jsonpath解析數(shù)據(jù)
hosts = 'https://api.weixin.qq.com' # 主機(jī)地址 # 獲取token get_param_dict = { "grant_type":"**********", "appid":"*************", "secret":"***************" } response = requests.get('%s/cgi-bin/token'%hosts,params=get_param_dict) json_obj = response.json() # json數(shù)據(jù)解析:從一個(gè)json體中取出需要的數(shù)據(jù),就叫json數(shù)據(jù)解析 token_id = jsonpath.jsonpath(json_obj,'$.access_token')[0] # 接口依賴,接口關(guān)聯(lián) print(token_id)
以上就是python requests模塊的使用的詳細(xì)內(nèi)容,更多關(guān)于python requests模塊的使用的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python 實(shí)現(xiàn)自動(dòng)化Excel報(bào)表的步驟
這篇文章主要介紹了Python 實(shí)現(xiàn)自動(dòng)化Excel報(bào)表的步驟,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04NDArray 與 numpy.ndarray 互相轉(zhuǎn)換方式
這篇文章主要介紹了NDArray 與 numpy.ndarray 互相轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05用Python編寫(xiě)一個(gè)漏洞驗(yàn)證腳本
大家好,本篇文章主要講的是用Python編寫(xiě)一個(gè)漏洞驗(yàn)證腳本,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下2022-02-02python global的創(chuàng)建和修改實(shí)例講解
在本篇文章里小編給大家整理了一篇關(guān)于python global的創(chuàng)建和修改實(shí)例講解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-09-09python dataframe astype 字段類(lèi)型轉(zhuǎn)換方法
下面小編就為大家分享一篇python dataframe astype 字段類(lèi)型轉(zhuǎn)換方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04Python中使用Flask、MongoDB搭建簡(jiǎn)易圖片服務(wù)器
這篇文章主要介紹了Python中使用Flask、MongoDB搭建簡(jiǎn)易圖片服務(wù)器,本文是一個(gè)詳細(xì)完整的教程,需要的朋友可以參考下2015-02-02