python 3.6 爬取json 文件報錯'bytes' object has no attribute 'read'

  使用json解析數據時,通常遇到這裏就會出現問題'bytes' object has no attribute 'read',這是由於使用的json內置函數不同,一個是load另一個是loads。

代碼如下:

import urllib.request
import json
import jsonpath
url = "http://www.lagou.com/lbs/getAllCitySearchLabels.json"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER "}
request = urllib.request.Request(url,headers = headers)
response = urllib.request.urlopen(request).read()
unicodester = json.load(response)
city_list = jsonpath.jsonpath(unicodester,"$..name")
for item in city_list:
    print(item)
報錯:

錯誤原因爲json.load()返回類型爲fp.read():


改正方法爲:

1、將源代碼代碼

response = urllib.request.urlopen(request).read()
unicodester = json.load(response)
改爲(去掉read())response = urllib.request.urlopen(request)unicodester = json.load(response)
2、將源代碼json.load(response)改爲json.loads(response)

輸出正確數據爲:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章