python requests模塊的使用示例
獲取token
# 使用微信公眾平臺舉例get_param_dict={ 'grant_type':'**************', 'appid':'**************', 'secret':'**************',}response = requests.get(url=’https://api.weixin.qq.com/cgi-bin/token’, # url地址 params=get_param_dict) # 參數print(response.content.decode(’utf-8’))模擬請求頭部信息
注:因為requests請求頭是以python,requests發起的,所以大部分接口都會需要手動添加頭部信息
# get 模擬請求頭部信息,(當你發現數據不對時,就模擬)# 以百度舉例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請求
import requests,json# requests模擬發送post請求# 使用微信公眾平臺舉例url_param_doct = {'access_token': '43_XcK_1rvR8VPgicGGzq7Vp2QrGx30Kwhy9SSShoVTQs11G_jP9aqhy2bwRQFuG2hYzkwVjphJFfPj8WYQR8vgfu5Xej7KaZBiyPDJ9sYoCKte78sqgtBdCf6N5S8QosNXBOFSEJnzLMbxJwCOTWAgAAANQU'}post_param_data = { 'tag' : { 'name' : '我是新標簽' }}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轉化 )print(response.content.decode(’utf-8’))requests上傳文件
import requests,os# post上傳文件current_path = os.path.dirname(__file__) # os模塊定位當前路徑excel_path = os.path.join(current_path,’..’,’data’,’j.xlsx’) # join拼接excel_file = {’file’:open(excel_path,’rb’)} # 做成字典,open打開文件 rb:只讀二進制response = requests.post(url=’https://2.python-requests.org/’, # requests官方實例文檔地址 files=excel_file) # files傳文件print( response.content.decode(’utf-8’) )requests設置代理
import requests# 設置代理:為什么設置代理?# 爬蟲類項目,有檢測機制# 防止公司系統有防灌水功能# 需要翻墻做接口的時候proxy_server = {’http’:’http://127.0.0.1:8888’, ’https’:’http://127.0.0.1:8888’} # 做一個字典proxy_user_pass = { ’https’:’http://uesrname:[email protected]:8888’ # 需要用戶跟密碼使用這個}response = requests.get(url= ’https://baidu.com’, proxies=proxy_server) # proxies設置代理關鍵字print(response.status_code)time模塊設置請求超時
如果一個請求很久沒有結果,就會讓整個項目的效率變得非常低,這個時候我們就需要對請求進行強制要求
讓他必須在特定的時間內返回結果,否則就報錯。
# 設置請求超時import requestsimport timeprint(time.time()) # 時間戳response = requests.get(url=’https://www.baidu.com’,timeout=3) # timeout=3: 請求如果在規定時間之內(3秒鐘內)沒有得到響應,就會拋出超時錯誤print(time.time())retrying模塊設置刷新
使用超時參數能夠加快我們整體的請求速度,但是在正常的網頁瀏覽過成功,如果發生速度很慢的情況,我們會做的選擇是刷新頁面
retrying模塊就可以幫助我們解決。使用retrying模塊提供的retry模塊
通過裝飾器的方式使用,讓被裝飾的函數反復執行retry中可以傳入參數stop_max_attempt_number,讓函數報錯后繼續重新執行
達到最大執行次數的上限,如果每次都報錯,整個函數報錯,如果中間有一個成功,程序繼續往后執行。
import requestsfrom retrying import retry# 如果函數連續調用三次都報錯,才會報錯,如果三次之中有一次成功,就成功@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設置
好處:能夠訪問登錄后的頁面
壞處:一套cookie往往對應的是一個用戶的信息,請求太頻繁有更大的可能性被對方識別為爬蟲如何解決 ?使用多個賬號
# 使用requests提供的session模塊import requests# 構造formdata表單數據,填寫自己的賬號和密碼post_data = { 'username': 'xxxxx', 'password': 'xxxxx'}# session的使用: 在請求之前創建session對象session = requests.Session()# 后續的請求都由session來發起,因為session中保存了用戶的登陸信息session.post(url='https://www.baidu.com', data=post_data)response = session.get('https://www.baidu.com')# 使用session請求登陸后的界面print(response.content.decode())處理證書認證錯誤
import requests# 方式一:不驗證證書,報警告,返回200requests.packages.urllib3.disable_warnings()# 直接解決爆紅警告# 方式二不驗證證書,報警告,返回200 ,后面拼接verify=False,加這個控制臺報警的話,就在加上方式一response = requests.get(’https://www.12306.cn’,verify=False)print(response.content.decode(’utf-8’))# 方式三:安裝pyopenssl 安裝之后就不會報錯# pip3 install -U requests[security] response = requests.get(’https://www.12306.cn’)print(response.content.decode(’utf-8’))# 方式四: 加上證書 公司內部 問開發要xxx.crt文件 ,最穩妥response = requests.get(’https://www.12306.cn’,cert=(’/path/server.crt’, ’/path/key’))requests+jsonpath解析數據
hosts = ’https://api.weixin.qq.com’ # 主機地址# 獲取tokenget_param_dict = { 'grant_type':'**********', 'appid':'*************', 'secret':'***************'}response = requests.get(’%s/cgi-bin/token’%hosts,params=get_param_dict)json_obj = response.json() # json數據解析:從一個json體中取出需要的數據,就叫json數據解析token_id = jsonpath.jsonpath(json_obj,’$.access_token’)[0] # 接口依賴,接口關聯print(token_id)
以上就是python requests模塊的使用的詳細內容,更多關于python requests模塊的使用的資料請關注好吧啦網其它相關文章!
相關文章: