项目说明
- 导入requests模块,执行HTTP命令;
- 导入json模块,对数据进行解码,文件f.write写入时,必须是string类型;
- with open as :文件操作语句;
- 列表类型;
- 构建天气封装函数;
import requests import json def getAreaWeather(code): url = 'https://restapi.amap.com/v3/weather/weatherInfo' r = requests.get(url, params={'city': '{}'.format(code), 'key': '4d9a765939a2b76588a3341c***'}) # print(r.url) # print(r.text) res = json.loads(r.text) with open('{}.txt'.format(code), 'w+') as f: # 写入本地文件,并按区域城市代码命名 f.write(json.dumps(res, ensure_ascii=False)) # 区域代码列表 area = ['330211', '330212', '330213'] # 执行循环程序 for i in area: getAreaWeather(i) print("天气情况:SUCCESS")
lockdatav Done !