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

yipeiwu_com4年前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 爬虫爬取指定博客的所有文章

自上一篇文章 Z Story : Using Django with GAE Python 后台抓取多个网站的页面全文 后,大体的进度如下: 1.增加了Cron: 用来告诉程序每隔30分...

python爬虫基础教程:requests库(二)代码实例

get请求 简单使用 import requests ''' 想要学习Python?Python学习交流群:973783996满足你的需求,资料都已经上传群文件,可以自行下载! ''...

Python实现爬取逐浪小说的方法

本文实例讲述了Python实现爬取逐浪小说的方法。分享给大家供大家参考。具体分析如下: 本人喜欢在网上看小说,一直使用的是小说下载阅读器,可以自动从网上下载想看的小说到本地,比较方便。最...

Python爬虫实例扒取2345天气预报

Python爬虫实例扒取2345天气预报

寒假里学习了一下Python爬虫,使用最简单的方法扒取需要的天气数据,对,没听错,最简单的方法。甚至没有一个函数封装。。 网址:http://tianqi.2345.com/wea_hi...

实例讲解Python爬取网页数据

一、利用webbrowser.open()打开一个网站: >>> import webbrowser >>> webbrowser.open('...