Python爬蟲例項扒取2345天氣預報

2022-09-28 16:36:19 字數 1904 閱讀 4486

寒假裡學習了一下python爬蟲,使用最簡單的方法扒取需要的天氣資料,對,沒聽錯,最簡單的方法。甚至沒有乙個函式封裝。。

**:火狐中右鍵檢視網頁源**,沒有發現天氣資料,因此推斷網頁採用的json格式資料。

右擊->檢視元素->網路->js,找到了位置

用python爬蟲**為json格式資料儲存下來,**如下:

#-*- 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 = ""+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()

扒取存到本地:

zxbzzpzr因為是剛學,學一點就動手實踐了一下,還沒有學到json的轉換,直接使用的正則匹配,提取json中的資料,直接列印

提取轉換json檔案中的資料python**:

#-*- coding:utf-8 -*-

import json

import re

import time

year = [2014]

month = [1]

for y in year:

for m in month:

程式設計客棧 """

2023年2月15日終於改成功。

是因為正則匹配後的編碼問題,導致輸出時無法顯示。

在每個正則匹配的元組後新增 .decode('gbk').encode('utf-8'),成功輸出

"""

content = fread.read()

pattern = re.compile(',',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執行

使用正則處理的一大問題就是格式不整齊,總會漏掉一些資料。可能是由於匹配的速度過快導致部分資料缺失,但是通過time.sleep() 睡眠依舊不能解決問題。

由此可以看程式設計客棧出正則匹配時的缺陷,待以後使用python中專門用於處理json資料的包以後,再重新試一下

本文標題: python爬蟲例項扒取2345天氣預報

本文位址:

Python爬蟲例項,爬取小說

import pprint import requests from bs4 import beautifulsoup 獲取原始碼 defget source url r requests.get url if r.status code 200 print r.status code 錯誤 rai...

python爬蟲例項 爬取歌單

學習自 從零開始學python 爬取酷狗歌單,儲存入csv檔案 直接上源 含注釋 import requests 用於請求網頁獲取網頁資料 from bs4 import beautifulsoup 解析網頁資料 import time time庫中的sleep 方法可以讓程式暫停 import c...

Python 爬蟲例項(4) 爬取網易新聞

自己閒來無聊,就爬取了網易資訊,重點是分析網頁,使用抓包工具詳細的分析網頁的每個鏈結,資料儲存在sqllite中,這裡只是簡單的解析了新聞頁面的文字資訊,並未對資訊進行解析 僅供參考,不足之處請指正 coding utf 8 import random,re import sqlite3 impor...