由于http://www.weather.com.cn/data/sk/网址不可用,帮我优化以下的代码,要求更换的网址不需要我的API密钥 def queryWeather(self): cityCode = self.getCityCode() rep = requests.get('http://www.weather.com.cn/data/sk/' + cityCode + '.html') rep.encoding = 'utf-8' res = rep.json() print(res) cur_city = self.ui.comb2.currentText() cur_region = self.ui.comb3.currentText() msg1 = '城市: %s市' % cur_city + '\n' msg2 = '风向: %s' % res['weatherinfo']['WD'] + '\n' msg3 = '温度: %s' % res['weatherinfo']['temp'] + ' 度' + '\n' msg4 = '风力: %s' % res['weatherinfo']['WS'] + '\n' msg5 = '湿度: %s' % res['weatherinfo']['SD'] + '\n' if cur_city == cur_region: result = msg1 + msg2 + msg3 + msg4 + msg5 else: msg_region = '区: %s区' % cur_region + '\n' result = msg1 + msg_region + msg2 + msg3 + msg4 + msg5 self.ui.textResult.setText(result)
时间: 2024-01-02 17:03:06 浏览: 125
可以尝试使用其他天气数据API,比如和风天气API(https://www.heweather.com/),或者是使用其他天气数据网站的API接口。以下是修改后的代码示例:
```python
def queryWeather(self):
cityCode = self.getCityCode()
rep = requests.get('https://free-api.heweather.net/s6/weather/now?location=' + cityCode + '&key=YOUR_KEY_HERE')
rep.encoding = 'utf-8'
res = rep.json()
print(res)
cur_city = self.ui.comb2.currentText()
cur_region = self.ui.comb3.currentText()
msg1 = '城市: %s市' % cur_city + '\n'
msg2 = '风向: %s' % res['HeWeather6'][0]['now']['wind_dir'] + '\n'
msg3 = '温度: %s' % res['HeWeather6'][0]['now']['tmp'] + ' 度' + '\n'
msg4 = '风力: %s' % res['HeWeather6'][0]['now']['wind_sc'] + '\n'
msg5 = '湿度: %s' % res['HeWeather6'][0]['now']['hum'] + '\n'
if cur_city == cur_region:
result = msg1 + msg2 + msg3 + msg4 + msg5
else:
msg_region = '区: %s区' % cur_region + '\n'
result = msg1 + msg_region + msg2 + msg3 + msg4 + msg5
self.ui.textResult.setText(result)
```
这里使用了和风天气提供的API接口,需要替换掉代码中的YOUR_KEY_HERE为自己的API密钥。同时也需要注意,和风天气提供的API返回的JSON数据格式可能与原始代码中使用的天气数据API返回的JSON格式不同,需要根据实际情况进行修改。
阅读全文