#coding=utf-8
from city import city
#若此处无法引用,则缺少#coding=utf-8
from urllib import request
#python3
import json
cityname = input("你想查哪个城市的天气?\n")
citycode = city.get(cityname)
if citycode:
try:
url = ("http://www.weather.com.cn/data/cityinfo/%s.html" % citycode)
page = request.urlopen(url).read().decode('utf-8')
content = str(page)
print(type(content))
data = json.loads(content)
print(type(data))
print(data)
result = data['weatherinfo']
str_temp = ('%s\n%s ~ %s') % (result['weather'], result['temp1'], result['temp2'])
print(str_temp)
except:
print("查询失败.")
else:
print("没有找到该城市")
以上程序中所用到的知识点如下:
#位置:文件开头 #说明所使用的python文件编码 #'='必须和coding之间没有空格
#从city.py中引用city内容
#存储城市对应代码的文件 #网上找来的资源:https://pan.baidu.com/s/1c0Nw4m
#直接用urllib.request模块的urlopen()获取页面
#网页的数据格式为bytes类型 #需要先用decode('utf-8')解码,再转换成str类型才能分析
#查看括号内部内容的数据类型
用法:json.loads(字符串) #将满足json格式的字符串转成字典