【Web_接口測試_Python3_編碼解碼】天氣預報接口獲取天氣信息,編碼轉換,自動化測試案例

#!/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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章