python + requests-- response content coding format and setting

Response content



We can read the contents of the server response. Again GitHub time line, for example:

>>> import requests

>>> r = requests.get('https://api.github.com/events')

>>> r.text

u'[{"repository":{"open_issues":0,"url":"https://github.com/...

Requests will automatically decode content from the server. Most unicode character set can be seamlessly decoded.



After the request is made, Requests will make an educated guess based on the encoded HTTP response header.



When you visit the r.text, Requests will use its presumed text encoding. You can find out what encoding Requests to use, and can use r.encoding property to change it:

>>> r.encoding # returns encoding format 'utf-8'                            

R.encoding = >>> 'the ISO-8859-1'      # encoding format set




If you change the code, whenever you visit r.text, Request all will use the new value of r.encoding.

You may wish to modify down in case of using a special encoding logic calculation of the encoded text.

Such as HTTP and XML itself can specify the encoding. In this case, you should use r.content to find the code, and then set r.encoding to the corresponding code. This will correct the code resolution r.text.


----------------------------------------------------------------------------

import requests

response = requests.get("https://www.baidu.com")



print (response.url) # returns the requested URL: HTTPS: // www.baidu.com/ 

Print (response.status_code) # fetch response status code: 200

print (response.encoding) # Returns the current encoding format: the ISO -8859-1

response.encoding = 'UTF-. 8'                  # encoding format set

print (response.encoding) # returns: UTF -8    -step instructions on setting success



print(response.content)       #返回:b'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8>
                               
                                      <meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer>

Results of the:


https://www.baidu.com/

200

ISO-8859-1

utf-8


b'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8>

<meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer>

=============================================================================================================================

 

Guess you like

Origin www.cnblogs.com/xiaobaibailongma/p/12339895.html