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')