python每隔一小时获取一次天气预报
时间: 2023-08-24 20:33:10 浏览: 46
可以使用Python中的第三方库requests和bs4来实现每隔一小时获取一次天气预报的功能。具体步骤如下:
1.安装requests和bs4库
```
pip install requests
pip install bs4
```
2.编写Python程序
```python
import requests
from bs4 import BeautifulSoup
import time
while True:
# 发送请求
url = 'https://www.tianqi.com/beijing/'
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.36'}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
# 解析数据
soup = BeautifulSoup(response.text, 'html.parser')
weather = soup.find('div', class_='wea_weather clearfix').em.getText()
temperature = soup.find('div', class_='wea_weather clearfix').b.getText()
print('天气:', weather)
print('温度:', temperature)
# 每隔一小时执行一次
time.sleep(3600)
```
这段代码会每隔一小时获取一次北京的天气预报,并打印出来。你可以根据自己的需求修改城市名称和打印方式。同时,使用try...except语句可以增加程序的稳定性,避免因为网络等原因导致程序崩溃。