Python实现抓取城市的PM2.5浓度和排名

本文给大家介绍的是一则使用Python实现抓取城市的PM2.5数据和排名,

主机环境:(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_right span")  # 空气质量等级
   result = soup.find("div",class_ ='bi_aqiarea_bottom')   # 空气质量描述
   print city.text + u'AQI指数:' + aqi.text + u'\n空气质量:' + quality[0].text + result.text
   print '*'*20 + ctime() + '*'*20
def one_thread():   # 单线程
   print 'One_thread Start: ' + ctime() + '\n'
   getPM25('hefei')
   getPM25('shanghai')
def two_thread():   # 多线程
   print 'Two_thread Start: ' + ctime() + '\n'
   threads = []
   t1 = threading.Thread(target=getPM25,args=('hefei',))
   threads.append(t1)
   t2 = threading.Thread(target=getPM25,args=('shanghai',))
   threads.append(t2)
   for t in threads:
       # t.setDaemon(True)
       t.start()
if __name__ == '__main__':
   one_thread()
   print '\n' * 2
   two_thread()


02131908_4vXp.jpg

02131908_je99.jpg


转载于:https://my.oschina.net/kyo4321/blog/596189

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值