当前位置 : 主页 > 编程语言 > python >

python3中的unicode_escape

来源:互联网 收集:自由互联 发布时间:2022-07-05
一. 响应的两种方式 在使用python3的requests模块时,发现获取响应有两种方式 其一,为文本响应内容, r.text 其二,为二进制响应内容,r.content 在《Python学习手册》中,是这样解释的 '''

一. 响应的两种方式

在使用python3的requests模块时,发现获取响应有两种方式

  • 其一,为文本响应内容, r.text
  • 其二,为二进制响应内容,r.content

在《Python学习手册》中,是这样解释的

'''Python 3.X带有3种字符串对象类型——一种用于文本数据,两种用于二进制数据:

  • str表示Unicode文本(8位的和更宽的)
  • bytes表示二进制数据
  • bytearray,是一种可变的bytes类型'''

也就是说,r.text实际上就是Unicode的响应内容,而r.content是二进制的响应内容,看看源码怎么解释

@property
def text(self):
"""Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using
``chardet``.

The encoding of the response content is determined based solely on 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`` appropriately before accessing this property.
"""

大体的意思是说,r.text方法返回的是用unicode编码的响应内容。响应内容的编码取决于HTTP消息头,如果你有HTTP之外的知识来猜测编码,你应该在访问这个属性之前设置合适的r.encoding,也就是说,你可以用r.encoding来改变编码,这样当你访问r.text ,Request 都将会使用r.encoding的新值

>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

我们看看r.content的源码

@property
def content(self):
"""Content of the response, in bytes."""

r.content返回的是字节形式的响应内容

二. 问题的提出与解决

当用requests发送一个get请求时,得到的结果如下:

import requests

url = "xxx"
params = "xxx"
cookies = {"xxx": "xxx"}

res = requests.request("get", url, params=params, cookies=cookies)
print(res.text)

python3中的unicode_escape_python

那么,问题来了,\u表示的那一串unicode编码,它是什么原因造成的,请参考​​知乎相关回答​​,该如何呈现它的庐山真面目?

print(res.text.encode().decode("unicode_escape"))

python3中的unicode_escape_python_02

这个unicode_escape是什么?将unicode的内存编码值进行存储,读取文件时在反向转换回来。这里就采用了unicode-escape的方式

 

当我们采用res.content时,也会遇到这个问题:

import requests

url = "xxx"
params = "xxx"
cookies = {"xxx": "xxx"}

res = requests.request("get", url, params=params, cookies=cookies)
print(res.content)

python3中的unicode_escape_python_03

解决的办法就是

print(res.content.decode("unicode_escape"))

python3中的unicode_escape_python_04

三. 总结

1. str.encode()  把一个字符串转换为其raw bytes形式

    bytes.decode()   把raw bytes转换为其字符串形式

2. 遇到类似的编码问题时,先检查响应内容text是什么类型,如果type(text) is bytes,那么

text.decode('unicode_escape')

如果type(text) is str,那么

text.encode('latin-1').decode('unicode_escape')

 

 

参考资料

​​https://www.zhihu.com/question/26921730​​

 


上一篇:python递归中的return
下一篇:没有了
网友评论