python爬取空气质量指标_Python实现抓取城市的PM2.5浓度和排名

本文介绍了使用Python的BeautifulSoup4库从www.pm25.com抓取PM2.5数据,包括城市空气质量排名。示例代码对比了单线程和多线程(以合肥和上海为例)获取数据的效率,并简单讨论了上海的空气质量问题。
摘要由CSDN通过智能技术生成

主机环境:(Python2.7.9 / Win8_64 / bs4)

利用BeautifulSoup4来抓取 www.pm25.com 上的PM2.5数据,之所以抓取这个网站,是因为上面有城市PM2.5浓度排名(其实真正的原因是,它是百度搜PM2.5出来的第一个网站!)

程序里只对比了两个城市,所以多线程的速度提升并不是很明显,大家可以弄10个城市并开10个线程试试。

最后吐槽一下:上海的空气质量怎么这么差!!!

PM25.py

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# by ustcwq

import urllib2

import threading

from time import ctime

from bs4 import BeautifulSoup

def getPM25(cityname):

site = 'http://www.pm25.com/' + cityname + '.html'

html = urllib2.urlopen(site)

soup = BeautifulSoup(html)

city = soup.find(class_ = 'bi_loaction_city')   # 城市名称

aqi = soup.find("a",{"class","bi_aqiarea_num"})  # AQI指数

quality = soup.select(".bi_aqiarea_r

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
全国的空气质量信息,可以通过访问国家环保部网站(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中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值