python之jsonpath的使用
import json import jsonpath import requests url="https://www.lagou.com/lbs/getAllCitySearchLabels.json" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"} html=requests.get(url,headers=headers).text #把json形式的字符串转换成python格式 unicodestr=json.loads(html) #利用jsonpath按照指定格式取出内容 city_list=jsonpath.jsonpath(unicodestr,"$..name") #把python形式的字符串转换成json格式用dumps #禁用ascii编码格式,返回unicode字符串,方便使用 city_array=json.dumps(city_list,ensure_ascii=False) with open("lagoucity.json","w") as f: f.write(city_array.encode("utf-8"))