最近在基於python3.6.5 的環境使用scrapy框架爬蟲獲取json數據,返回的數據是unicode格式的,在spider里面的parse接口中打印response.text出來如下:
class TestSpider(Spider):
......
def parse(self, response):
print(response.text)
結果如下:
{
"status":"true",
"last_view_time":null,
"message":"",
"shown_offset":0,
"articles":[
{
"channel":"\u8d44\u8bafnew",
"comments":113,
"created_at":"09\u670828\u65e5",
"desc":" \u00a0 \u00a0 \u00a0 \u00a0 \u00a0\u00a0\u5173\u6ce8ITValue\uff0c\u67e5\u770b\u4f01\u4e1a\u7ea7\u5e02\u573a\u6700\u65b0\u9c9c\u3001\u6700\u5177\u4ef7\u503c\u7684\u62a5\u9053\uff01\u4e2d\u56fd\u667a\u6167\u529e\u516c\u54c1\u724c\u6df1\u5733\u5e02\u84dd\u51cc
.......
python3版本開始取消了string的decode方法,不能像以前一樣使用類似mystring.decode(“utf-8”) 的方式轉碼。
其實可以繞一下解決,先編碼再解碼:
def parse(self, response):
datas = json.dumps(response.text, ensure_ascii= False, indent=4, separators=(',', ': '))
json_data = json.loads(datas).encode('utf-8').decode('unicode_escape')
print(json_data)
關鍵在於:
mystr.encode('utf-8').decode('unicode_escape')
最后打印內容正常了:
{
"status":"true",
"last_view_time":null,
"message":"",
"shown_offset":0,
"articles":[
{
"channel":"默認",
"comments":25,
"created_at":"09月28日",
"desc":" 了解快捷鍵能夠提升您的生產力。這里有一些實用的 Ubuntu 快捷鍵助您像專業人士一樣使用 Ubuntu。-- Abhishek Prakash有用的原文鏈接請訪問文末的...","downs":0,"id":"82879369","isexpert":0,"sourcetype":1,"tag":"","title"
............