python爬取网页,出现中文乱码情况
代码如下
import requests
# 请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
}
url = "https://img.juexiaotime.com/jsons/product/2022123010/dce104c8a0bf4f049641bc5dbdf8f27d.json"
r = requests.get(url, headers=headers)
r.encoding = 'utf-8'
print(r.text)
求指点
以下回答参考GPT并且由Bony-整理:
你的代码已经指定了请求的编码为utf-8,但是在实际的情况下可能会出现网页返回的编码和你指定的编码不一致的情况,所以可以尝试使用自动检测编码的方式,如下所示:
import requests
# 请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
}
url = "https://img.juexiaotime.com/jsons/product/2022123010/dce104c8a0bf4f049641bc5dbdf8f27d.json"
r = requests.get(url, headers=headers)
r.encoding = r.apparent_encoding
print(r.text)
如果还是出现中文乱码的情况,可以尝试使用其他编码,比如gbk等,具体编码需要根据实际情况来确定。
一、定义字典和列表并直接输出,结果输出结果中文是乱码展示
d={'name':'lily','age':18,'sex':'女','no':1121}
e=['你好',1,'apple']
print d
print e
输出结果:
{'age': 18, 'no': 1121, 'name': 'lily', 'sex': '\xe5\xa5\xb3'}
['\xe4\xbd\xa0\xe5\xa5\xbd', 1, 'apple']
二、解决办法:
d={'name':'lily','age':18,'sex':'女','no':1121}
e=['你好',1,'apple']
print json.dumps(d,encoding='utf-8',ensure_ascii=False)
print json.dumps(e,encoding='utf-8',ensure_ascii=False)
输出结果:
{"age": 18, "no": 1121, "name": "lily", "sex": "女"}
["你好", 1, "apple"]