溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Requests庫如何在Python中應(yīng)用

發(fā)布時(shí)間:2021-04-01 17:09:39 來源:億速云 閱讀:159 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)Requests庫如何在Python中應(yīng)用,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

0 安裝

pip install requests

1 發(fā)送請求

r=requests.get('https://www.baidu.com')
print r.status_code,r.text
r=requests.post('http://httpbin.org/post')
r=requests.put('http://httpbin.org/put')
r=requests.delete('http://httpbin.org/delete')
r=requests.head('http://httpbin.org/head')
r=requests.options('http://httpbin.org/')

2 發(fā)送get參數(shù)

param={'key1':value1,'key2':value2}
r=requests.get('http://www.baidu.com/',params=param)

3 發(fā)送post參數(shù)

param={'key1':value1,'key2':value2}
r=requests.post('http://www.baidu.com/',params=param) #表單格式
r=requests.post('http://www.baidu.com/',json=param) #json格式數(shù)據(jù)
file= {'file':open('1.txt','rb')}
r=reuqest.post('http://httpbin.org/post',files=file)

4 文件下載

with open('1.pic','wb') as pic:
  for chunk in response.iter_content(size):
    pic.write(chunk)

5 攜帶header

header={'key1':value1,'key2':value2}
r=requests.get('http://www.baidu.com/',headers=header)

6 攜帶cookie

cookie={'key1':value1,'key2':value2}
r=requests.get('http://www.baidu.com/',cookies=cookie)

7 重定向

默認(rèn)requests是允許重定向的,并將重定向的歷史保存在response.history數(shù)組中
如果不需要重定向,可以通過開關(guān)來關(guān)閉

r=requests.get('http://www.baidu.com/',allow_redirects=False)

8 使用代理

使用socks代理需要安裝三方擴(kuò)展包

pip install requests[socks]
proxy={
  'http':'http://127.0.0.1:8000',
  'https':'https://127.0.0.1:8080'
  'http':'socks5://user:pass@127.0.0.1:8132'
}
r=requests.get('https://www.github.com/',proxies=proxy)

9 設(shè)置連接超時(shí)

r=requests.get('http://www.baidu.com/',timeout=2.5)

10 ssl證書

證書驗(yàn)證

requests.get('https://kennethreitz.com', verify=True)
requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))

如果指定本地證書及密鑰,則密鑰需要是解密的。

11 requests對象

r.url
r.text
r.headers

12 Response對象

response.request 對應(yīng)的請求對象
response.raw socket上直接獲得的數(shù)據(jù)
response.text 根據(jù)響應(yīng)頭進(jìn)行解碼的文本數(shù)據(jù)
response.content 不解碼,返回二進(jìn)制數(shù)據(jù)
response.json() 對返回?cái)?shù)據(jù)進(jìn)行json解碼
response.headers 詞典形式存儲(chǔ)返回的headers
response.cookies 詞典形式存儲(chǔ)返回的cookies

以上就是Requests庫如何在Python中應(yīng)用,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI