本文實例講述了Python Requests庫基本用法。分享給大家供大家參考,具體如下:
requests是python的一個http client庫,提供了一套簡捷的API供開發者使用。下面簡單介紹一下其安裝和使用。這里是官方文檔。
0 安裝
pip install requests
1 發送請求
r=requests.get('https://www.baidu.com')print r.status_code,r.textr=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 發送get參數
param={'key1':value1,'key2':value2}r=requests.get('http://www.baidu.com/',params=param)
3 發送post參數
param={'key1':value1,'key2':value2}r=requests.post('http://www.baidu.com/',params=param) #表單格式r=requests.post('http://www.baidu.com/',json=param) #json格式數據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 重定向
默認requests是允許重定向的,并將重定向的歷史保存在response.history
數組中
如果不需要重定向,可以通過開關來關閉
r=requests.get('http://www.baidu.com/',allow_redirects=False)
8 使用代理
使用socks代理需要安裝三方擴展包
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 設置連接超時
r=requests.get('http://www.baidu.com/',timeout=2.5)
10 ssl證書
證書驗證
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
對應的請求對象response.raw socket
上直接獲得的數據response.text
根據響應頭進行解碼的文本數據response.content
不解碼,返回二進制數據response.json()
對返回數據進行json解碼
新聞熱點
疑難解答