python爬取长三角地区空气质量的代码
时间: 2023-04-05 11:03:23 浏览: 65
我可以回答这个问题。以下是一个简单的 Python 爬虫代码,可以爬取长三角地区的空气质量数据:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://www.pm25.in/yangpu'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
aqi = soup.find('div', {'class': 'span1'}).find('div', {'class': 'value'}).text.strip()
pm25 = soup.find('div', {'class': 'span1', 'title': '细颗粒物'}).find('div', {'class': 'value'}).text.strip()
pm10 = soup.find('div', {'class': 'span1', 'title': '可吸入颗粒物'}).find('div', {'class': 'value'}).text.strip()
print('AQI:', aqi)
print('PM2.5:', pm25)
print('PM10:', pm10)
```
这个代码可以爬取上海杨浦区的空气质量数据,你可以根据需要修改 URL 和解析 HTML 的代码来爬取其他地区的数据。
相关问题
python爬取长三角地区空气质量的全部爬虫部分代码
我可以回答这个问题。以下是一个简单的 Python 爬虫代码,可以爬取长三角地区空气质量数据:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://www.pm25.in/shanghai'
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'}
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
table = soup.find('table', {'class': 'table table-striped table-bordered'})
trs = table.find_all('tr')[1:]
for tr in trs:
tds = tr.find_all('td')
city = tds[0].text.strip()
aqi = tds[1].text.strip()
print(city, aqi)
```
这段代码可以爬取上海市的空气质量数据,你可以根据需要修改 `url` 参数来爬取其他城市的数据。
如何用python爬取空气质量_python爬取全国空气质量信息 具体代码 以及实现方法
要爬取全国的空气质量信息,可以通过访问国家环保部网站(http://www.mee.gov.cn/),找到空气质量相关的数据。
具体实现方法:
1. 首先,需要用requests模块向国家环保部网站发起请求,获取相应的HTML页面。
```python
import requests
url = "http://www.mee.gov.cn/ywgz/fgbz/bzwb/dqhjbh/dqhjzlbz/index.shtml"
response = requests.get(url)
html = response.content.decode("utf-8")
```
2. 接下来,需要使用BeautifulSoup模块解析HTML页面,获取想要的数据。
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
table = soup.find("table", {"class": "content"})
trs = table.find_all("tr")
for tr in trs[1:]:
tds = tr.find_all("td")
city = tds[1].get_text()
aqi = tds[2].get_text()
print(city, aqi)
```
3. 最后,将获取的数据存储到本地文件中。
```python
with open("aqi.txt", "w", encoding="utf-8") as f:
for tr in trs[1:]:
tds = tr.find_all("td")
city = tds[1].get_text()
aqi = tds[2].get_text()
f.write(city + "\t" + aqi + "\n")
```
完整代码如下:
```python
import requests
from bs4 import BeautifulSoup
url = "http://www.mee.gov.cn/ywgz/fgbz/bzwb/dqhjbh/dqhjzlbz/index.shtml"
response = requests.get(url)
html = response.content.decode("utf-8")
soup = BeautifulSoup(html, "html.parser")
table = soup.find("table", {"class": "content"})
trs = table.find_all("tr")
with open("aqi.txt", "w", encoding="utf-8") as f:
for tr in trs[1:]:
tds = tr.find_all("td")
city = tds[1].get_text()
aqi = tds[2].get_text()
f.write(city + "\t" + aqi + "\n")
```
这段代码可以爬取国家环保部网站上的全国空气质量信息,并将其保存到本地文件aqi.txt中。