Python爬蟲實(shí)例扒取2345天氣預(yù)報
寒假里學(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()扒取存到本地:
因?yàn)槭莿倢W(xué),學(xué)一點(diǎn)就動手實(shí)踐了一下,還沒有學(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日終于改成功。 是因?yàn)檎齽t匹配后的編碼問題,導(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運(yùn)行
使用正則處理的一大問題就是,格式不整齊,總會漏掉一些數(shù)據(jù)。可能是由于匹配的速度過快導(dǎo)致部分?jǐn)?shù)據(jù)缺失,但是通過time.sleep() 睡眠依舊不能解決問題。
由此可以看出正則匹配時的缺陷,待以后使用Python中專門用于處理json數(shù)據(jù)的包以后,再重新試一下
相關(guān)文章
python使用Psutil模塊實(shí)現(xiàn)獲取計(jì)算機(jī)相關(guān)信息
psutil 是一個跨平臺的庫,用于獲取進(jìn)程和系統(tǒng)運(yùn)行狀態(tài)的信息,這篇文章主要為大家詳細(xì)介紹了python如何調(diào)用psutil模塊實(shí)現(xiàn)獲取計(jì)算機(jī)相關(guān)信息,有需要的小伙伴可以了解下2023-11-11

python神經(jīng)網(wǎng)絡(luò)使用tensorflow構(gòu)建長短時記憶LSTM

python動態(tài)進(jìn)度條的實(shí)現(xiàn)代碼

python web自制框架之接受url傳遞過來的參數(shù)實(shí)例

pytorch: Parameter 的數(shù)據(jù)結(jié)構(gòu)實(shí)例

簡單快捷:NumPy入門教程的環(huán)境設(shè)置

Python+Redis從零打造分布式鎖實(shí)戰(zhàn)示例