beautifulsoup爬取天气网
时间: 2023-10-28 20:06:52 浏览: 33
使用BeautifulSoup爬取天气网可以分为以下步骤:
1. 发送请求获取网页源代码
2. 解析网页源代码
3. 提取所需数据并存储
下面是具体代码:
```python
import requests
from bs4 import BeautifulSoup
# 发送请求获取网页源代码
url = 'http://www.weather.com.cn/weather/101280101.shtml'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 解析网页源代码
weather_list = soup.select('.t .sky')
date_list = soup.select('.t .week')
temperature_list = soup.select('.t .tem')
# 提取所需数据并存储
for i in range(len(date_list)):
weather = weather_list[i].text.strip()
date = date_list[i].text.strip()
temperature = temperature_list[i].text.strip()
print(date, weather, temperature)
```
在这个例子中,我们使用了`requests`库来发送请求获取网页源代码,使用了`BeautifulSoup`库来解析网页源代码。然后,我们使用CSS选择器来选择所需的元素,最后提取数据并输出。