1. 程式人生 > 其它 >requests庫請求之細枝末節

requests庫請求之細枝末節

一、r.text

import requests
r = requests.get('githubcom/timeline.json')
print(r.text)
{"message":"Hello there, wayfaring stranger. If you're reading this then you probably didn't see our blog post a couple of years back announcing that this API would Go away: Git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.
","documentation_url":"developer.githubcom/v3/activity/events/#list-public-events"}

1、Requests會根據response.encoding來自動解碼來自伺服器的內容。大多數unicode字符集都能被無縫地解碼【unicode響應內容】。

2、請求發出後,Requests會基於HTTP頭部對響應的編碼作出有根據的推測

3、當你訪問r.text之時,Requests會使用響應中其推測的文字編碼。你可以找出response使用了什麼編碼,並且能夠使用response.encoding 屬性來改變它。

二、r.json()

Requests中也有一個內建的JSON解碼器,助你處理JSON資料:

import requests
r = requests.get('githubcom/timeline.json')
print(r.json())

r.json將返回的json格式字串解碼成python字典。r.text返回的utf-8的文字【python資料型別為str】。

三、r.content

如果請求返回的是二進位制的圖片,你可以使用r.content訪問請求響應體。

import requests
from PIL import Image
from StringIO import StringIO
r 
= requests.get('cn.python-requests.org/zh_CN/latest/_static/requests-sidebar.png')
# 讀取生成的二進位制資料【使用StringIO可以將r.content二進位制資料當作檔案來操作】--》讀取的結果為圖片 i
= Image.open(StringIO(r.content))
# 展示圖片 i.show()