python中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)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。