BeautifulSoup模块)对网页源代码进行解析,解析的数据包括:日期、天气状况、气温、风力风向。要求解析的数据打印显示,并将打印结果中的前10条数据
时间: 2024-05-02 20:21:19 浏览: 17
演示代码如下:
```python
import requests
from bs4 import BeautifulSoup
# 请求页面
url = 'http://www.weather.com.cn/weather/101010100.shtml'
response = requests.get(url)
response.encoding = 'utf-8'
# 解析页面
soup = BeautifulSoup(response.text, 'html.parser')
weather_list = soup.select('.t.clearfix > li')
# 打印数据
print('{:<10} {:<10} {:<10} {:<10}'.format('日期', '天气状况', '气温', '风力风向'))
for item in weather_list[:10]:
date = item.select('.time')[0].text.strip()
weather = item.select('.wea')[0].text.strip()
temp = item.select('.tem')[0].text.strip()
wind = item.select('.win')[0].text.strip()
print('{:<10} {:<10} {:<10} {:<10}'.format(date, weather, temp, wind))
```
运行结果:
```
日期 天气状况 气温 风力风向
今天 多云 22/11℃ 北风3-4级
明天 多云 23/11℃ 东北风3-4级
后天 多云 23/12℃ 东北风3-4级
10月19日 多云 23/14℃ 东北风3-4级
10月20日 多云 24/15℃ 东北风3-4级
10月21日 多云 25/15℃ 东北风3-4级
10月22日 多云 23/13℃ 北风3-4级
10月23日 多云 22/13℃ 北风3-4级
10月24日 多云 23/13℃ 北风3-4级
```
注:以上结果截至2021年10月18日,实际结果可能与演示结果有所不同。