python爬取北上广深空气质量
时间: 2023-08-20 20:06:56 浏览: 54
您好!要爬取北上广深的空气质量数据,可以使用 Python 的 requests 库和 BeautifulSoup 库来实现。具体的步骤如下:
1. 首先,需要确定一个网站来获取数据。建议使用国家环保部网站(http://www.cnemc.cn/)上的空气质量指数查询页面,该页面包含了北上广深等城市的空气质量数据。
2. 使用 requests 库发送 HTTP 请求,获取网页源代码。代码示例:
```
import requests
url = 'http://www.cnemc.cn/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
html = response.text
```
3. 使用 BeautifulSoup 库解析网页源代码,获取空气质量数据。代码示例:
```
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
city_list = soup.select('#city_list')
for city in city_list:
city_name = city.select('.city_name')[0].text.strip()
aqi = city.select('.aqivalue')[0].text.strip()
print(city_name, aqi)
```
其中,city_list 是一个包含所有城市信息的列表,每个城市信息包含城市名称和空气质量指数。
希望这个回答能够帮到您!