登录  /  注册

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

php中文网
发布: 2016-06-06 11:22:14
原创
1232人浏览过

主机环境:(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()

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

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号