python爬取天气预报
时间: 2023-09-24 08:10:05 浏览: 45
你可以使用Python的requests库和BeautifulSoup库来爬取天气预报。
首先,你需要找到一个能够提供天气预报数据的网站,例如中国气象局的天气预报网站(http://www.weather.com.cn/)。然后,使用requests库发起一个HTTP请求,获取网页内容。接下来,使用BeautifulSoup库解析网页内容,提取出需要的天气预报信息。
以下是一个简单的示例代码:
```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')
weather = soup.find('p', class_='wea').text
temperature = soup.find('p', class_='tem').text.replace('\n', '').strip()
print('天气:{}'.format(weather))
print('温度:{}'.format(temperature))
```
在上面的代码中,我们使用requests库发起一个HTTP请求,获取北京市的天气预报网页内容。然后,使用BeautifulSoup库解析网页内容,找到天气和温度信息,并打印出来。
你也可以通过循环获取多天的天气预报,或者利用其他的Python库(例如pandas和matplotlib)进行数据分析和可视化。