Turn from "51361006
I've been thinking about the difference between the content and the Text property of requests, there's no difference from the print results.
Look at the Source:
@property def text(self): "" " Content of the response, in Unicode. If response.encoding is None, encoding'll be guessed using ' Chardet '. The encoding of the response content is determined based solely in HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-http knowledge to make a better guess at the encoding, you should set ' R.encoding ' appr Opriately before accessing. "" " #content的完整代码就不贴了. @property def content(self): "" " content of the response, in bytes. " ""
Resp.text returns the Unicode type of data.
Resp.content returns the bytes type, which is the binary data.
That is, if you want to take text, you can pass the R.text.
If you want to take pictures, file, you can pass r.content.
(Resp.json () returns JSON-formatted data)
# 例如下载并保存一张图片import requestsjpg_url = ‘http://img2.niutuku.com/1312/0804/0804-niutuku.com-27840.jpg‘content = requests.get(jpg_url).contentwith open(‘demo.jpg‘, ‘wb‘) as fp: fp.write(content)
---------------------------------------------------------------------------------------以下是正确的
1. Focus on understanding
response.textThe type returned isstr
response.contentThe returned type is the type bytes that can be decode() converted by method to bytes str type
Recommended response.content.decode() way to use: to get the appropriate HTML page
2. Extended Comprehension
- Response.text
Decoding type: Based on the HTTP header of the response encoding to make an educated guess, the inferred text encoding
How to modify the encoding method:response.encoding = ‘gbk‘
- Response.content
Decode type: not specified
How to modify the encoding method:response.content.decode(‘utf8‘)
The difference between the content and text methods of Python requests