当前位置: 移动技术网 > IT编程>脚本编程>Python > Python实现抓取城市的PM2.5浓度和排名

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

2019年06月14日  | 移动技术网IT编程  | 我要评论
主机环境:(python2.7.9 / win8_64 / bs4) 利用beautifulsoup4来抓取 上的pm2.5数据,之所以抓取这个网站,是因为上面有城市p

主机环境:(python2.7.9 / win8_64 / bs4)

利用beautifulsoup4来抓取 上的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()

以上就是本文所述的全部内容了,希望大家能够喜欢。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网