python requests text content_python request text 和 content的区别
1 test和content簡(jiǎn)介resp.text返回的是Unicode型的數(shù)據(jù)。
resp.content返回的是bytes型也就是二進(jìn)制的數(shù)據(jù)。
如果你想取文本,可以通過r.text。
如果想取圖片,文件,則可以通過r.content。
2 如何查看網(wǎng)頁的編碼
方式一:
import requests
import chardet
s=requests.get('https://hao.360.cn/?h_lnk')
print(chardet.detect(s.content))
方式二:
import requests
s=requests.get('https://hao.360.cn/?h_lnk')
print(s.encoding)
意思是requests.text是根據(jù)網(wǎng)頁的響應(yīng)來猜測(cè)編碼,如果服務(wù)器不指定的話,默認(rèn)編碼是"ISO-8859-1"所以這是為什么有些時(shí)候用 response.text 返回的是亂碼的原因。
可以用response.encoding看一下他猜測(cè)的編碼是啥。然后用response.encoding = 'utf-8'來設(shè)置編碼
實(shí)例如下:
import requests
response=requests.get('http://www.qq.com')
response.encoding
>>'GB2312'
response.encoding="UTF-8"
response.encoding
>> 'UTF-8'
3 大部分情況建議使用.text,因?yàn)轱@示的是漢字,但有時(shí)會(huì)顯示亂碼,這時(shí)需要用.text.encode('utf-8'),中文常用utf-8和GBK,GB2312等。這樣可以手工選擇文字編碼方式。
所以簡(jiǎn)而言之,.text是現(xiàn)成的字符串,.content還要解碼,但是.text不是所有時(shí)候顯示都正常,這是就需要用.content進(jìn)行手動(dòng)解碼。
如:
方式一:content解碼
方式二:test編碼
總結(jié)
以上是生活随笔為你收集整理的python requests text content_python request text 和 content的区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pytorch 查看当前学习率_pyto
- 下一篇: pythonprint end_pyth