python爬虫爬取不同城市的天气数据
时间: 2023-06-28 11:06:23 浏览: 107
你可以使用 Python 的 requests 库和 BeautifulSoup 库来爬取天气数据。步骤如下:
1. 打开网站,找到需要爬取的数据的网址。
2. 使用 requests 库发送请求,获取网页源代码。
3. 使用 BeautifulSoup 库解析网页源代码,找到需要爬取的数据所在的 HTML 标签。
4. 提取数据并保存。
下面是一个示例代码,可以爬取不同城市的天气数据:
```python
import requests
from bs4 import BeautifulSoup
# 定义要爬取的城市列表
city_list = ['北京', '上海', '广州', '深圳']
for city in city_list:
# 构造 URL
url = 'http://www.weather.com.cn/weather/{}.shtml'.format(city)
# 发送请求
response = requests.get(url)
# 解析网页源代码
soup = BeautifulSoup(response.content, 'html.parser')
# 找到需要爬取的数据所在的 HTML 标签,并提取数据
weather = soup.find(class_='wea').text.strip()
temperature = soup.find(class_='tem').text.strip()
# 输出数据
print('{}: {},{}'.format(city, weather, temperature))
```
这个代码会输出每个城市的天气和温度,例如:
```
北京: 晴,13/26℃
上海: 阵雨,15/22℃
广州: 多云,24/32℃
深圳: 多云,25/31℃
```