国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python爬蟲實例扒取2345天氣預(yù)報

2020-01-04 15:46:25
字體:
供稿:網(wǎng)友

寒假里學(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,爬蟲,天氣預(yù)報

用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ù)的包以后,再重新試一下


注:相關(guān)教程知識閱讀請移步到python教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 鄂尔多斯市| 体育| 谷城县| 景德镇市| 花莲县| 策勒县| 阜新| 南乐县| 永川市| 尤溪县| 日土县| 高安市| 乳山市| 修武县| 房山区| 东港市| 兴山县| 井研县| 高雄县| 万盛区| 遂溪县| 临夏市| 五峰| 三台县| 甘肃省| 海兴县| 永安市| 那坡县| 都兰县| 临高县| 烟台市| 临海市| 寻甸| 云南省| 疏附县| 商水县| 新干县| 柘城县| 陕西省| 元朗区| 台湾省|