requests模塊

一、安裝Requests

pip install requests

二、發(fā)送請求與傳遞參數(shù)

帶參數(shù)請求:

import requests

requests.get('http://www.dict.baidu.com/s', params={'wd': 'python'}) ? ? ? ? ?#GET參數(shù)實例

requests.post('http://www.itwhy.org/wp-comments-post.php', data={'comment': '測試post'}) ? #POST參數(shù)實例

POST發(fā)送JSON數(shù)據(jù):

import requests

impoet json

r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'}))

print(r.json())

定制header:

import requests

import json

data = {'some': 'data'}

headers = {'content-type': 'application/json',

'User-Agent': 'Mozilla/5.0(x11; Ubuntu; Linux x86_64; rv:22.0) GEcko/20100101

firefox/22.0'}

r = request.post('https://api.github.com/some/endpoint', data=data, headers=headers)

print(r.text)

三、Response對象

使用requests方法后,會返回一個response對象,其存儲了服務器響應的內(nèi)容。

r.status_code 響應狀態(tài)碼

r.raw 返回原始響應體

r.content 字節(jié)方式的響應體,會自動為你解碼gzip和deflate壓縮

r.text 字符串方式的響應體,會自動根據(jù)響應頭部的字符編碼進行解碼

r.headers 以字典對象存儲服務器的響應頭,但是這個字典比較特殊,字典鍵不區(qū)分大小寫,若鍵不存在返回None

特殊方法

r.json() ?Requests中內(nèi)置JSON解碼器

r.raise_for_starus() ?失敗請求拋出異常

例:

import requests

URL = 'http://ip.taobao.com/service/getIpinfo.php' ?#淘寶IP地址庫API

try:

??????? r = requests.get(URL, params={'ip': '8.8.8.8'}, timeout=1)

??????? r.raise_for_status() ? ? ? ? ?#如果狀態(tài)碼不是200,就主動拋出異常

??????? except requests.RequestException as e:

??????? print(e)

else:

??????? result = r.json()

??????? print(type(result), result, sep='\n')

四、上傳文件

使用Requests模塊,上傳文件也是如此簡單的,文件的類型會自動進行處理:

import requests

url = 'http://127.0.0.1:8080/upload'

files = {'file': open('/home/lyb/sjzl.mpg', 'rb')}

# files = {'file': ('xxxx,jpg', open('/home/lyb/sjzl.mpg', 'rb'))} ?#設置文件名

r = requests.post(url, files = files)

print(r.text)

直接把字符串當文件進行上傳:

import requests

url = 'http://127.0.0.1:5000/upload'

files = {'file':('test.txt', b'Hello Requests.')}

r = requests.post(url, files=files)

print(r.text)

五、身份驗證

基本身份認證(HTTP Basic Auth):

import requests

from requests.auuth import HTTPBasicAuth

r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd'))

# r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=('user', 'passwd')) ?#簡寫

print(r.json())

摘要式身份認證

requests.get(URL, auth = HTTPDigestAuth('user', 'pass'))

六、Cookies與會話對象

發(fā)送cookies到服務器,攜帶cookies參數(shù):

import requests

cookies = {'testCookies': 'Hello'}

r = requests.get('http://www.google.com' cookies = cookies)

print(r.json())

七、超時與異常

timeout 僅對連接過程有效,與響應體的下載無關。

requests.get('http://githhub.com', timeout=0.001)

所有Requests顯式拋出的異常都繼承自 requests.exceptions.RequestException:ConnectionError、HTTPError、TimeoutTooManyRedirects

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容