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爬虫爬取新浪微博内容示例【基于代理IP】

Python爬虫爬取新浪微博内容示例【基于代理IP】

本文实例讲述了Python爬虫爬取新浪微博内容。分享给大家供大家参考,具体如下: 用Python编写爬虫,爬取微博大V的微博内容,本文以女神的微博为例(爬新浪m站:https://m.w...

Python使用Selenium+BeautifulSoup爬取淘宝搜索页

使用Selenium驱动chrome页面,获得淘宝信息并用BeautifulSoup分析得到结果。 使用Selenium时注意页面的加载判断,以及加载超时的异常处理。 impor...

Python抓取手机号归属地信息示例代码

前言 本文给大家介绍的是利用Python抓取手机归属地信息,文中给出了详细的示例代码,相信对大家的理解和学习很有帮助,以下为Python代码,较为简单,供参考。 示例代码 # -*-...

利用python爬取散文网的文章实例教程

利用python爬取散文网的文章实例教程

本文主要给大家介绍的是关于python爬取散文网文章的相关内容,分享出来供大家参考学习,下面一起来看看详细的介绍: 效果图如下: 配置python 2.7 bs4 requ...

python爬虫 线程池创建并获取文件代码实例

本实例主要进行线程池创建,多线程获取、存储视频文件 梨视频:利用线程池进行视频爬取 #爬取梨视频数据 import requests import re from lxml impo...