python做http时,想把中文数据写入文件的编码问题

本文详细介绍如何使用Python的urllib库发送HTTP请求,并通过JSON模块处理返回的中文数据,包括编码转换、数据读写及解析。同时,文章还解释了JSON与Python数据类型之间的转换方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值