主機環(huán)境:(Python2.7.9 / Win8_64 / bs4)
利用BeautifulSoup4來抓取 www.pm25.com 上的PM2.5數(shù)據(jù),之所以抓取這個網(wǎng)站,是因為上面有城市PM2.5濃度排名(其實真正的原因是,它是百度搜PM2.5出來的第一個網(wǎng)站?。?
程序里只對比了兩個城市,所以多線程的速度提升并不是很明顯,大家可以弄10個城市并開10個線程試試。
最后吐槽一下:上海的空氣質(zhì)量怎么這么差!?。?
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指數(shù)
??? quality = soup.select(".bi_aqiarea_right span")? # 空氣質(zhì)量等級
??? result = soup.find("div",class_ ='bi_aqiarea_bottom')?? # 空氣質(zhì)量描述
??? print city.text + u'AQI指數(shù):' + aqi.text + u'\n空氣質(zhì)量:' + 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()
以上就是本文所述的全部內(nèi)容了,希望大家能夠喜歡。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
