python爬取当前天气的代码
时间: 2023-05-26 18:02:09 浏览: 105
一个简单Python 代码 爬取天气信息
以下是一个示例Python程序,可以使用它从中国天气网中爬取当前的天气情况:
```python
import requests
def get_weather(city):
url = 'http://www.weather.com.cn/weather/{}.shtml'.format(city)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
r = requests.get(url, headers=headers)
r.encoding = 'utf-8'
weather_dict = {}
try:
# 解析城市和时间信息
city = r.json()['weatherinfo']['city']
time = r.json()['weatherinfo']['time']
weather_dict['城市'] = city
weather_dict['时间'] = time
# 解析天气信息
weather = r.json()['weatherinfo']['weather']
temp = r.json()['weatherinfo']['temp']
wind = r.json()['weatherinfo']['WD'] + ' ' + r.json()['weatherinfo']['WS']
weather_dict['天气'] = weather
weather_dict['温度'] = temp
weather_dict['风力'] = wind
return weather_dict
except:
return None
if __name__ == '__main__':
city = '北京' # 城市名称
weather_dict = get_weather(city)
if weather_dict:
for key, value in weather_dict.items():
print(key + ':', value)
```
在运行此代码之前,请确保您已安装了`requests`库。
此程序将检索指定城市的当前天气情况,并打印其城市,时间,天气,温度和风力信息。它使用HTTP请求获取有关天气的JSON响应,然后解析它以获得所需的信息。
阅读全文