如何用python爬取15天天气数据
时间: 2023-09-17 19:07:32 浏览: 57
你可以使用Python中的requests和BeautifulSoup库来爬取15天的天气数据。以下是一些基本的步骤:
1. 使用requests库向天气网站发送请求,获取页面的HTML源代码。
2. 使用BeautifulSoup库解析HTML源代码,提取所需的数据。
3. 将提取的数据保存到文件或数据库中。
下面是一个示例代码,其中我们以“北京”为例,爬取“中国天气网”上的15天天气数据:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://www.weather.com.cn/weather/101010100.shtml'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 获取15天天气数据的列表
weather_list = soup.find('div', {'id': '7d'}).find_all('li')
for weather in weather_list:
# 获取日期、天气状况、最高温度和最低温度
date = weather.find('h1').text
condition = weather.find('p', {'class': 'wea'}).text
high_temp = weather.find('p', {'class': 'tem'}).find('span').text
low_temp = weather.find('p', {'class': 'tem'}).find('i').text
print(f'{date}: {condition}, 最高温度{high_temp}℃, 最低温度{low_temp}℃')
```
这样,你就可以获取到北京未来15天的天气数据了。如果你需要爬取其他城市的天气数据,只需要修改url的参数即可。