1.已经知道这种情况:
2.在爬取知乎专栏文章时,response的内容是json格式的,print(response.read().decode('utf-8'))输出得中文部分都是以Unicode码表示的(就像上图中的s);用BeautifulSoup 提取response的text,然后用print()输出,结果还是Unicode码,print(text)为什么不像1中那样输出对应中文呢?那要怎样才能输出对应的中文呢?
输出结果:
3.可以用json.loads(resp.read().decode('utf-8'))将response转化成字典,那样上述Unicode码也就显示为中文了,但这样就不能用BeautifulSoup了。
--------------------------------------------------------------------
回答:
先检查text是什么类型
如果type(text) is bytes,那么text.decode('unicode_escape')
如果type(text) is str,那么
text.encode('latin-1').decode('unicode_escape')