Spider——关于数据转码问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37049781/article/details/82020206

在爬虫的过程中,编码问题常常会遇到,数据在你面前总是隔了层纱,要么抛出个ascii错误,要么就是保存下来和打印出来的不一样

拉勾小案例

举个例子来探讨一下。
将拉勾网的城市分类信息保存到本地。
地址:拉勾城市信息
城市信息

# _*_ coding:utf-8 _*_
import urllib2
import jsonpath
import json

url = "http://www.lagou.com/lbs/getAllCitySearchLabels.json"
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36"}

request = urllib2.Request(url,headers = headers)
response = urllib2.urlopen(request)
print response.read()

这里写图片描述

html = response.read()
# 将返回内容转化为python中的数据对象(unicode编码)
py_obj = json.loads(html)
# 获取所有城市名(unicode编码)
all_city = jsonpath.jsonpath(py_obj,"$..name")

这里写图片描述
这里写图片描述
到这里我们已经获取到了所有的城市名,并且也知道了城市名是采用的unicode编码,如果用print打印出来的话就是我们很熟悉的汉字了。在这里根据需要存储到文件中

array = json.dumps(all_city)
with open('city_info.json',"w") as f:
    f.write(array)

如果这样保存,那么数据是肯定有些问题的,会显示
这里写图片描述
所以要进行一下编码处理再持久化存储

# json.dumps在处理数据的时候会默认以ascii的方式处理
array = json.dumps(all_city, ensure_ascii=False)
# 保存时需要encode一下
with open('city_info.json',"w") as f:           
    f.write(array.encode("utf-8"))

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_37049781/article/details/82020206