溫馨提示×

溫馨提示×

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

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

request中response.text和response.content的區(qū)別及怎么用

發(fā)布時(shí)間:2022-02-24 16:56:55 來源:億速云 閱讀:298 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要講解了“request中response.text和response.content的區(qū)別及怎么用”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“request中response.text和response.content的區(qū)別及怎么用”吧!

1.response.text

- 類型:str

- 解碼類型: 根據(jù)HTTP 頭部對(duì)響應(yīng)的編碼作出有根據(jù)的推測,推測的文本編碼

- 如何修改編碼方式:response.encoding=”gbk”

2. response.content

- 類型:bytes

- 解碼類型: 沒有指定

- 如何修改編碼方式:response.content.deocde(“utf-8”)

3.獲取網(wǎng)頁源碼的通用方式:

response.content.decode()
response.content.decode(“GBK”)

解碼方式可以根據(jù)響應(yīng)頭中找到Content-Type:text/html;charset=utf-8或者網(wǎng)頁源碼中content="text/html;charset=utf-8''來決定.

response.text

以上三種方法從前往后嘗試,能夠100%的解決所有網(wǎng)頁解碼的問題

所以:更推薦使用**response.content.deocde()**的方式獲取響應(yīng)的html頁面

補(bǔ)充:python3中requests 常用response

看代碼吧~

import requests
res = requests.get("http://127.0.0.1:9092")

print(res.status_code) # 200
print(res.url) # http://127.0.0.1:9092/
print(res.headers) # {'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '10', 'Date': 'Sat, 22 Dec 2018 13:36:16 GMT', 'Connection': 'keep-alive'}
print(res.cookies) # <RequestsCookieJar[<Cookie cid=hello world for 127.0.0.1/>]>
print(res.text) # 8248154254
print(res.content) # b'8248154254' 寫圖片
print(res.cookies['cid']) # hello world

# 爬取 圖片
r1 = requests.get('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545496551516&di=8ed19596bc72aa87299ed7f234830128&imgtype=0&src=http%3A%2F%2Fimg5.duitang.com%2Fuploads%2Fitem%2F201107%2F31%2F20110731155631_htMcs.jpg')
b = r1.content
with open('hao.jpg','wb') as f:
    f.write(b)

感謝各位的閱讀,以上就是“request中response.text和response.content的區(qū)別及怎么用”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)request中response.text和response.content的區(qū)別及怎么用這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

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

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

AI