python requests模塊的使用示例
獲取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打開文件 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è)置代理?# 爬蟲類項(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:[email protected]: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)求很久沒有結(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 requestsimport timeprint(time.time()) # 時(shí)間戳response = requests.get(url=’https://www.baidu.com’,timeout=3) # timeout=3: 請(qǐng)求如果在規(guī)定時(shí)間之內(nèi)(3秒鐘內(nèi))沒有得到響應(yīng),就會(huì)拋出超時(shí)錯(cuò)誤print(time.time())retrying模塊設(shè)置刷新
使用超時(shí)參數(shù)能夠加快我們整體的請(qǐng)求速度,但是在正常的網(wǎng)頁瀏覽過成功,如果發(fā)生速度很慢的情況,我們會(huì)做的選擇是刷新頁面
retrying模塊就可以幫助我們解決。使用retrying模塊提供的retry模塊
通過裝飾器的方式使用,讓被裝飾的函數(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 requestsfrom 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 responseretrying_requests = get_response('https://www.baidu.com')print(retrying_requests.content.decode())cookie設(shè)置
好處:能夠訪問登錄后的頁面
壞處:一套cookie往往對(duì)應(yīng)的是一個(gè)用戶的信息,請(qǐng)求太頻繁有更大的可能性被對(duì)方識(shí)別為爬蟲如何解決 ?使用多個(gè)賬號(hào)
# 使用requests提供的session模塊import requests# 構(gòu)造formdata表單數(shù)據(jù),填寫自己的賬號(hào)和密碼post_data = { 'username': 'xxxxx', 'password': 'xxxxx'}# session的使用: 在請(qǐng)求之前創(chuàng)建session對(duì)象session = requests.Session()# 后續(xù)的請(qǐng)求都由session來發(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())處理證書認(rèn)證錯(cuò)誤
import requests# 方式一:不驗(yàn)證證書,報(bào)警告,返回200requests.packages.urllib3.disable_warnings()# 直接解決爆紅警告# 方式二不驗(yàn)證證書,報(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’))# 方式四: 加上證書 公司內(nè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ī)地址# 獲取tokenget_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)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問題……2. asp批量添加修改刪除操作示例代碼3. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效4. Vue中nvm-windows的安裝與使用教程(親測(cè))5. 刪除docker里建立容器的操作方法6. 三個(gè)不常見的 HTML5 實(shí)用新特性簡(jiǎn)介7. 推薦一個(gè)好看Table表格的css樣式代碼詳解8. jsp實(shí)現(xiàn)簡(jiǎn)單用戶7天內(nèi)免登錄9. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲10. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法
