這個編碼格式真的是很鬧心啊,看來真的得深入學習一下編碼格式,要不這各種格式錯誤。
這個編碼還和編輯器有關系,最開始的時候實在sublime Text里編輯的代碼,運行起來卡卡的,特別順暢,但突然發現它不支持raw_input和input,所以令臨時換到了python官方提供的idle中。之后就出現了各種奇葩編碼錯誤。。。。。。
程序大概意思就是,你輸入一個城市的拼音,它就會返回這個城市的空氣污染情況啊,有些城市可能會沒有,這個完全取決與網站上有那些城市啊,當你想退出的時候就輸入quit,就退出來了。
里面還有一個多線程的寫法,可以體驗一下單線程和多線程之間的速度是有很大差距的。。。
~~~
<span style="font-size:14px;"># -*- coding: utf-8 -*->
import urllib2
import threading
from time import ctime
import BeautifulSoup #besutifulsoup的第三版
import re
def getPM25(cityname):
site = 'http://www.pm25.com/city/' + cityname + '.html'
html = urllib2.urlopen(site)
soup = BeautifulSoup.BeautifulSoup(html)
city = soup.find("span",{"class":"city_name"}) # 城市名稱
aqi = soup.find("a",{"class":"cbol_aqi_num"}) # AQI指數
pm25 = soup.find("span",{"class":"cbol_nongdu_num_1"}) # pm25指數
pm25danwei = soup.find("span",{"class":"cbol_nongdu_num_2"}) # pm25指數單位
quality = soup.find("span",{"class":re.compile('cbor_gauge_level\d$')}) # 空氣質量等級
result = soup.find("div",{"class":'cbor_tips'}) # 空氣質量描述
replacechar = re.compile("<.*?>") #為了將<>全部替換成空
space = re.compile(" ")
print city.string + u'\nAQI指數:' + aqi.string+ u'\nPM2.5濃度:' + pm25.string + pm25danwei.string + u'\n空氣質量:' + quality.string + space.sub("",replacechar.sub('',str(result))).decode('utf-8')
print '*'*20 + ctime() + '*'*20
def one_thread(cityname1): # 單線程
print 'One_thread Start: ' + ctime() + '\n'
getPM25(cityname1)
def two_thread(): # 多線程
print 'Two_thread Start: ' + ctime() + '\n'
threads = []
t1 = threading.Thread(target=getPM25,args=('beijing',))
threads.append(t1)
t2 = threading.Thread(target=getPM25,args=('shenyang',))
threads.append(t2)
for t in threads:
# t.setDaemon(True)
t.start()
if __name__ == '__main__':
print "*"*20+"welcome to 京東放養的爬蟲"+"*"*20
while True:
cityname1 = raw_input("請輸入想要查看的城市名稱:(例如:beijing)")
if cityname1 == 'quit':
break
one_thread(cityname1)
#print '\n' * 2
#two_thread(cityname)
</span>
~~~