python爬虫天气预报_Python爬虫实例扒取2345天气预报
寒假里學(xué)習(xí)了一下Python爬蟲,使用最簡(jiǎn)單的方法扒取需要的天氣數(shù)據(jù),對(duì),沒聽錯(cuò),最簡(jiǎn)單的方法。甚至沒有一個(gè)函數(shù)封裝。。
網(wǎng)址:http://tianqi.2345.com/wea_history/53892.htm
火狐中右鍵查看網(wǎng)頁(yè)源代碼,沒有發(fā)現(xiàn)天氣數(shù)據(jù),因此推斷網(wǎng)頁(yè)采用的json格式數(shù)據(jù)。
右擊->查看元素->網(wǎng)絡(luò)->JS,找到了位置
用Python爬蟲下載為json格式數(shù)據(jù)存儲(chǔ)下來,代碼如下:
#-*- 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)就動(dòng)手實(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)致輸出時(shí)無法顯示。
在每個(gè)正則匹配的元組后添加 .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)行
使用正則處理的一大問題就是,格式不整齊,總會(huì)漏掉一些數(shù)據(jù)??赡苁怯捎谄ヅ涞乃俣冗^快導(dǎo)致部分?jǐn)?shù)據(jù)缺失,但是通過time.sleep() 睡眠依舊不能解決問題。
由此可以看出正則匹配時(shí)的缺陷,待以后使用Python中專門用于處理json數(shù)據(jù)的包以后,再重新試一下
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的python爬虫天气预报_Python爬虫实例扒取2345天气预报的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用python数据分析的研究意义_大数
- 下一篇: linux 查看磁盘空间_Linux下删