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

yipeiwu_com5年前Python爬虫

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

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

相关文章

python脚本爬取字体文件的实现方法

前言 大家应该都有所体会,为了提高验证码的识别准确率,我们当然要首先得到足够多的测试数据。验证码下载下来容易,但是需要人脑手工识别着实让人受不了,于是我就想了个折衷的办法——自己造验证码...

python访问抓取网页常用命令总结

python访问抓取网页常用命令 简单的抓取网页: import urllib.request url="http://google.cn/" response=urllib....

python爬虫的一个常见简单js反爬详解

前言 我们在写爬虫是遇到最多的应该就是js反爬了,今天分享一个比较常见的js反爬,这个我已经在多个网站上见到过了。 我把js反爬分为参数由js加密生成和js生成cookie等来操作浏览器...

python爬虫之遍历单个域名

即使你没听说过“维基百科六度分隔理论”,也很可能听过“凯文 • 贝肯 (Kevin Bacon)的六度分隔值游戏”。在这两个游戏中,目标都是把两 个不相干的主题(在前一种情况...

python3实现爬取淘宝美食代码分享

python3实现爬取淘宝美食代码分享

环境: ubuntu16.04 python3.5 python库: selenium, pyquery,pymongo, re 要求: 设置×××面浏览器访问,并将商品列表存入mo...