寒假里學(xué)習(xí)了一下Python爬蟲,使用最簡單的方法扒取需要的天氣數(shù)據(jù),對,沒聽錯,最簡單的方法。甚至沒有一個函數(shù)封裝。。
網(wǎng)址:http://tianqi.2345.com/wea_history/53892.htm
火狐中右鍵查看網(wǎng)頁源代碼,沒有發(fā)現(xiàn)天氣數(shù)據(jù),因此推斷網(wǎng)頁采用的json格式數(shù)據(jù)。
右擊->查看元素->網(wǎng)絡(luò)->JS,找到了位置

用Python爬蟲下載為json格式數(shù)據(jù)存儲下來,代碼如下:
#-*- coding:utf-8 -*- import urllib2 import json months = [1,2,3,4,5,6,7,8,9,10,11,12] years = [2011,2012,2013,2014,2015,2016] city = [53892] #邯鄲代碼53892 for y in years: for m in months: for c in city: url = "http://tianqi.2345.com/t/wea_history/js/"+str(c)+"_"+str(y)+str(m)+".js?qq-pf-to=pcqq.c2c" print url html = urllib2.urlopen(url) srcData = html.read() #JsonData = json.loads(srcData) file = open("d:/json/"+str(c)+"handan/weather"+str(c)+"_"+str(y)+str(m)+".json","w") file.write(srcData) file.close() 扒取存到本地:因為是剛學(xué),學(xué)一點就動手實踐了一下,還沒有學(xué)到j(luò)son的轉(zhuǎn)換,直接使用的正則匹配,提取json中的數(shù)據(jù),直接打印
提取轉(zhuǎn)換json文件中的數(shù)據(jù)Python代碼:
#-*- coding:utf-8 -*- import json import re import time Year = [2014] Month = [1] for y in Year: for m in Month: """ 2016年2月15日終于改成功。 是因為正則匹配后的編碼問題,導(dǎo)致輸出時無法顯示。 在每個正則匹配的元組后添加 .decode('gbk').encode('utf-8'),成功輸出 """ content = fRead.read() pattern = re.compile('{ymd:/'(.*?)/',bWendu:/'(.*?)/',yWendu:/'(.*?)/',tianqi:/'(.*?)/',fengxiang:/'(.*?)/',fengli:/'(.*?)/'},',re.S) items = re.findall(pattern,content) for item in items: print item[0].decode('gbk').encode('utf-8'),","+item[1].decode('gbk').encode('utf-8'),","+item[2].decode('gbk').encode('utf-8'),","+item[3].decode('gbk').encode('utf-8'),","+item[4].decode('gbk').encode('utf-8'),","+item[5].decode('gbk').encode('utf-8') time.sleep(0.1) fRead.close() 使用Sublime Text 3運行
使用正則處理的一大問題就是,格式不整齊,總會漏掉一些數(shù)據(jù)。可能是由于匹配的速度過快導(dǎo)致部分數(shù)據(jù)缺失,但是通過time.sleep() 睡眠依舊不能解決問題。
由此可以看出正則匹配時的缺陷,待以后使用Python中專門用于處理json數(shù)據(jù)的包以后,再重新試一下
新聞熱點
疑難解答
圖片精選