requests庫簡單的介紹

參考資料requests官方文檔,崔慶才的博客

requests是基于urllib3的一個用于發(fā)起http請求的庫。
這個庫相較于urllib更快,更易用。

1. 發(fā)送請求

1.1 簡單的嘗試

訪問百度,并打印返回值,及返回值的各個參數(shù):

import requests  # 一開始要導入 Requests 模塊
response = requests.get('http://www.baidu.com')  # 可以從response中獲取我們想要的信息
print(response.content.decode('utf-8'))
print(type(response))
print(response.text)
print(response.cookies)

1.2 發(fā)送帶參數(shù)的GET請求:

# 攜帶參數(shù)的get請求
import requests
data = {
    'name': 'wg',
    'age': 18
}
response = requests.get('http://httpbin.org/get', params=data)
print(response.url)  # http://httpbin.org/get?name=wg&age=18

在發(fā)送帶參數(shù)的GET請求時,requests允許我們使用params關鍵字參數(shù),以一個字符串字典來提供這些參數(shù)。我們打印拼接后的URL,會看到參數(shù)已經(jīng)拼接成功:

print(response.url)
# http://httpbin.org/get?name=wg&age=18

1.3 發(fā)送POST請求

# 發(fā)送post請求
response = requests.post('http://httpbin.org/post')

1.4 發(fā)送更復雜的POST請求

通常,你想要發(fā)送一些編碼為表單形式的數(shù)據(jù)——非常像一個 HTML 表單。要實現(xiàn)這個,只需簡單地傳遞一個字典給 data 參數(shù)。你的數(shù)據(jù)字典在發(fā)出請求時會自動編碼為表單形式:

import requests
data = {
    'key1': 'value1',
    'key2': 'value2'
}
response = requests.post('http://httpbin.org/post', data=data)
print(response.text)

打印結果如下:


post傳遞數(shù)據(jù).png

你還可以為 data 參數(shù)傳入一個元組列表。在表單中多個元素使用同一 key 的時候,這種方式尤其有效:

import requests
payload = (('key1', 'value1'), ('key1', 'value2'))
response = requests.post('http://httpbin.org/post', data=payload)
print(response.text)

打印結果如下:


多個元素使用同一個Key.png

1.5 發(fā)送別的HTTP請求

response = requests.delete('http://httpbin.org/delete')
response = requests.head('http://httpbin.org/get')
response = requests.options('http://httpbin.org/get')

2. 響應內(nèi)容

Requests會自動解碼來自服務器的響應。大多數(shù) unicode 字符集都能被無縫地解碼。
請求發(fā)出后,Requests 會基于 HTTP 頭部對響應的編碼作出有根據(jù)的推測。當你訪問 response.text之時,Requests 會使用其推測的文本編碼。你可以找出 Requests 使用了什么編碼,并且能夠使用 r.encoding 屬性來改變它。

2.1 二進制響應內(nèi)容

用requests獲取一張圖片:

import requests
response = requests.get('https://avatars3.githubusercontent.com/u/26769750?s=40&v=4')

打印content:

print(response.content)  # 打印content
打印content.png

打印content的類型:

print(type(response.content))  # 打印content的類型
<class 'bytes'>

把獲取到的二進制數(shù)據(jù),轉(zhuǎn)換為一張圖片:

import requests
response = requests.get('https://avatars3.githubusercontent.com/u/26769750?s=40&v=4')
print(response.content)
print(type(response.content))
with open('githubUserPic', 'wb') as f:
    f.write(response.content)
    f.close()

打開程序所在路徑,就會看到一張叫做“githubUserPic”的圖片了。

2.2 JSON響應內(nèi)容

Requests 中也有一個內(nèi)置的 JSON 解碼器,助你處理 JSON 數(shù)據(jù):

import requests
response = requests.get('https://api.github.com/events')
print(response.json())
如果 JSON 解碼失敗,response.json() 就會拋出一個異常。例如,響應內(nèi)容是 401 (Unauthorized),嘗試訪問 response.json() 將會拋出 ValueError: No JSON object could be decoded 異常。

需要注意的是,成功調(diào)用 response.json() 并**不**意味著響應的成功。有的服務器會在失敗的響應中包含一個 JSON 對象(比如 HTTP 500 的錯誤細節(jié))。這種 JSON 會被解碼返回。要檢查請求是否成功,請使用 response.raise_for_status() 或者檢查 response.status_code 是否和你的期望相同。

3. 設置請求頭

直接請求http://www.zhihu.com/explore,會請求失敗,并返回狀態(tài)碼400,表示錯誤請求服務器無法解析該請求。
設置請求頭,然后再次訪問:

import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36',
}
response = requests.get('http://www.zhihu.com/explore', headers=headers)
print(response.text)

就可以看到正常的返回了:


設置請求頭之后的返回.png

4. Cookie

如果某個響應中包含一些 cookie,你可以快速訪問它們:

import requests
response = requests.get('http://www.baidu.com')
print(response.cookies)

發(fā)送cookie到服務器:

import requests
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
response = requests.get(url, cookies=cookies)
print(response.text)

打印返回值:

{
  "cookies": {
    "cookies_are": "working"
  }
}

以上內(nèi)容只是簡單的整理,詳細的內(nèi)容還請參考requests官方文檔。

完。

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

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

  • 上一篇:8.Urllib庫基本使用下一篇:10.正則表達式基礎 requests是python實現(xiàn)的最簡單易用的H...
    在努力中閱讀 3,602評論 2 11
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,942評論 1 92
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,555評論 19 139
  • Getting Started Burp Suite 是用于攻擊web 應用程序的集成平臺。它包含了許多工具,并為...
    Eva_chenx閱讀 29,244評論 0 14
  • (其一) 當石榴花染紅了這五月 當梔子的香氣裊裊襲來 當粽葉和艾蒿清香彌漫 心中的端午已走到面前 吃上一口香香粘粘...
    打狗棒之天下無狗閱讀 269評論 0 0

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