5. 从网站http://www.weather.com.cn/jiangsu/index.shtml爬取江苏各城市的天气预报数据,并把爬取到的天气数据写入地文本文件weather.txt 代码
时间: 2024-02-04 13:02:59 浏览: 152
好的,以下是实现代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://www.weather.com.cn/jiangsu/index.shtml'
response = requests.get(url)
html = response.content.decode('utf-8')
soup = BeautifulSoup(html, 'html.parser')
cities = soup.find_all('div', class_='conMidtab2')
with open('weather.txt', 'w', encoding='utf-8') as f:
for city in cities:
city_name = city.find('div', class_='cityName').text.strip()
weather_items = city.find_all('ul')
for weather_item in weather_items:
date = weather_item.find('li', class_='time').text.strip()
weather = weather_item.find('li', class_='wea').text.strip()
temperature = weather_item.find('li', class_='tem').text.strip()
f.write(city_name + '\t' + date + '\t' + weather + '\t' + temperature + '\n')
```
该代码会从江苏天气预报页面中提取各城市的天气数据,并将数据写入到名为 `weather.txt` 的文本文件中。每行数据格式为:城市名称、日期、天气情况、温度。
阅读全文