在做http时,最后想把中文数据写入文件
import urllib.parse
import urllib.request
#url = “http://bigdata-api-fnw-release.topaas.enncloud.cn/internal/bigdata/weather/get_prediction?hourNum=1&cityId=101250101”
url = “http://bigdata-api-fnw-release.topaas.enncloud.cn”
interface = “/internal/bigdata/weather/get_prediction”
#定义请求数据,并且对数据进行赋值
values={}
values[‘hourNum’]= ‘1’
values[‘cityId’]= ‘101250101’
#对请求数据进行编码
data = urllib.parse.urlencode(values).encode(‘utf-8’)
print(type(data)) # 打印<class ‘bytes’>
print(data) # 打印b’hourNum=1&cityId=101250101’
若为post请求以下方式会报错TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.
Post的数据必须是bytes或者iterable of bytes,不能是str,如果是str需要进行encode()编码
data = urllib.parse.urlencode(values)
#print(type(data)) # 打印<class ‘str’>
#print(data) # 打印status=hq&token=C6AD7DAA24BAA29AE14465DDC0E48ED9
#将数据与url进行拼接
req = url + interface + ‘?’ + data
#打开请求,获取对象
response = urllib.request.urlopen(req)
#print(type(response)) # 打印<class ‘http.client.HTTPResponse’>
#打印Http状态码
status = response.status # 打印200
#读取服务器返回的数据,对HTTPResponse类型数据进行读取操作
the_page = response.read()
#中文编码格式打印数据
cc = the_page.decode(“utf-8”)
#json中有中文,需要注明编码格式encoding及ensure_ascii
import json
with open(“d:/tt.json”,“w”,encoding=‘utf-8’) as f:
json.dump(cc, f, ensure_ascii =False, indent=4)
with open(“d:/tt.json”, ‘r’, encoding=“utf-8”) as load_f:
load_dict = json.load(load_f)
print(load_dict)
介绍
json的主要方法有两种json.dumps和json.loads。详细说明可阅读这篇文章(https://www.cnblogs.com/bigberg/p/6430095.html
https://blog.youkuaiyun.com/weixin_44731100/article/details/90903110)
JSON在python中分别由list和dict组成。
这是用于序列化的两个模块:
json: 用于字符串和python数据类型间进行转换
pickle: 用于python特有的类型和python的数据类型间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load