【Web_接口爬虫_Python3_编码解码_request&chardet】天气预报接口获取天气信息,编码转换,自动化测试案例

#!/usr/bin/env/python3
# -*- coding:utf-8 -*-
'''
Author:leo
Date&Time:2019-09-20 and 12:35
FileName:20190920_07_接口获取天气预报.py
Description:...
'''

# 导入接口测试专用库
import requests
# 导入编码检查专用库
import chardet

# 获取接口地址
weatherUrl = r"http://www.weather.com.cn/data/sk/101190408.html"
response = requests.get(url=weatherUrl)
res = response.text
response = response.json()

# 直接转码要出现乱码,可以转码到非unicode,再转回来即刻显示中文
city = response['weatherinfo']['city'].encode('raw_unicode_escape').decode("utf-8")
temp = response['weatherinfo']['temp']
print(f"当前返回:{res.encode('raw_unicode_escape').decode('utf-8')}")
print(f"编码格式:{chardet.detect(res.encode('utf-8'))}")
print(f"当前城市:{city},当前温度:{temp}")

# -- 结果:
# 当前返回:{"weatherinfo":{"city":"太仓","cityid":"101190408","temp":"22.8","WD":"东风","WS":"小于3级","SD":"81%","AP":"1005.5hPa","njd":"暂无实况","WSE":"<3","time":"17:55","sm":"3.2","isRadar":"0","Radar":""}}
# 编码格式:{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
# 当前城市:太仓,当前温度:22.8

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值