日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python爬虫天气预报_Python爬虫实例扒取2345天气预报

發(fā)布時間:2024/9/15 python 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python爬虫天气预报_Python爬虫实例扒取2345天气预报 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

寒假里學(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)致部分?jǐn)?shù)據(jù)缺失,但是通過time.sleep() 睡眠依舊不能解決問題。

由此可以看出正則匹配時的缺陷,待以后使用Python中專門用于處理json數(shù)據(jù)的包以后,再重新試一下

與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖

總結(jié)

以上是生活随笔為你收集整理的python爬虫天气预报_Python爬虫实例扒取2345天气预报的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。