#!/usr/bin/env python # encoding: utf-8 import urllib2 # json 解析库,对应到lxml import json # json 解析语法,对应到xpath import jsonpath # 这是一个json的返回格式页面 url ="https://www.sojson.com/api/qqmusic/8446666" header = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"} request = urllib2.Request(url,headers=header) # 取出返回中的内容,返回的格式是字符串 html = urllib2.urlopen(request).read() # 将json形式的字符串转换成python形式的unicode字符串 result = json.loads(html) # 用来查找xsong_url中的内容 str_list = jsonpath.jsonpath(result,'$..xsong_url') for item in str_list: with open('save.txt', 'w') as f: f.write(item) # 禁用ascii编码格式,返回的Unicode字符串,方便操作 # dump()默认中文为ascii编码格式,ensure_ascii中在python2中默认为true array = json.dumps(str_list,ensure_ascii=False) with open("url.json",'w') as f: f.write(array.encode("utf-8"))
python中jsonpath解析使用
最新推荐文章于 2023-12-19 10:26:15 发布