簡述
再次進行分析抓取氣象數(shù)據(jù)練習西疤,本節(jié)主要抓取預報氣象數(shù)據(jù)。抓取數(shù)據(jù)請勿存檔甩鳄,商用請聯(lián)系官方很洋。
爬取對象
抓取中央氣象臺城市預報數(shù)據(jù)
城市預報數(shù)據(jù)
使用包
import pymssql # MS Sql Server 操作
from bs4 import BeautifulSoup
import time, os
import requests
import datetime
實現(xiàn)步驟
1底哗、抓取對象初步分析
- 通過
F12
捕獲頁面內(nèi)容岁诉,分析頁面加載內(nèi)容,得知目標對象主要分為兩部分跋选,點擊后續(xù)預測某日,下方切換顯示具體時刻哗蜈。
頁面分析
- 分析總結(jié)主體抓取步驟如下
Start
1前标、download_page("http://www.nmc.cn/f/rest/province") # 請求所有直轄市、省列表 list x
2距潘、download_page("http://www.nmc.cn/f/rest/province/x") # 請求 x 下所有城市列表 list y
3炼列、download_page("http://www.nmc.cnpublish/forecast/zzz/z.html"),# 請求城市 z 頁面內(nèi)容音比,并從中過濾出目標對象
4俭尖、循環(huán)目標對象中每天詳細預測數(shù)據(jù),存儲至數(shù)據(jù)庫
End_定時重復上述步驟
- 因?qū)︻A測全天數(shù)據(jù)中氣象氣溫數(shù)據(jù)含義不了解,估放棄全天數(shù)據(jù)抓取稽犁,僅抓取預測時刻數(shù)據(jù)
全天數(shù)據(jù)
2焰望、抓取對象深入分析
預測時刻數(shù)據(jù)
- 分析總結(jié)后續(xù)需注意以下問題
1、數(shù)據(jù)以表格形式顯示已亥,列頭為時刻(與常規(guī)數(shù)據(jù)存儲習慣相反)熊赖,后續(xù)讀取數(shù)據(jù)需按列分組
2、所有數(shù)據(jù)第一列為說明虑椎,后續(xù)為 8 個時刻數(shù)據(jù)(間隔 3 小時)震鹉;“今天”第一列為最近的時刻,后續(xù)所有日期數(shù)據(jù)第一列為 “08:00”捆姜,估涉及重復數(shù)據(jù)
3传趾、預測時刻中“23:00”以后,涉及日期整體加一天
4泥技、天氣氣象數(shù)據(jù)為圖片墨缘,需轉(zhuǎn)換為對應文字
3、問題對應實現(xiàn)偽代碼
- 按時間分組獲取數(shù)據(jù)
values_list = []
#定義不同的數(shù)據(jù) list 保存每列數(shù)據(jù)零抬,后續(xù)便于統(tǒng)一整合
value1_list = []
value2_list = []
......
for i,row_table in enumerate(day_html.find_all('div', attrs={'class': 'row'})):
for j,column_table in enumerate(row_table.find_all('div')):
if j == 1:
value1_list.append(text)
elif j == 2:
value2_list.append(text)
......
values_list.append(value1_list)
values_list.append(value2_list)
......
- 重復數(shù)據(jù)判斷
sql="select count(id) from Space0009A where column_0='%s' and column_1='%s' and column_2='%s' " %(publish_city,publish_time,f_sj)
isRepeat = ms.ExecQuery(sql.encode('utf-8'))
if isRepeat[0][0] == 0:
sql = "insert into Space0009A values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s') " %(publish_city,publish_time,f_sj,f_tqxx,f_qw,f_js,f_fs,f_fx,f_qy,f_sd,f_yl,f_njd)
ms.ExecNonQuery(sql.encode('utf-8'))
- 預測時刻日期區(qū)分
days_html = soup.find_all('div', attrs={'class':'hour3'})
flag_date = int(day_html["id"].replace('day','')) #day0 镊讼、day1......
forecast_date = datetime.datetime.strptime(publish_time,"%Y-%m-%d %H:%M").date() + datetime.timedelta(flag_date) #獲取預測日期
for i,row_table in enumerate(day_html.find_all('div', attrs={'class': 'row'})):
is_new_day = False
for j,column_table in enumerate(row_table.find_all('div')):
if i == 0:
if "日" in text:
text = str(forecast_date + datetime.timedelta(1)) +" "+ text.split('日')[1]
is_new_day = True
elif is_new_day:
text = str(forecast_date + datetime.timedelta(1)) + " " + text
else:
text = str(forecast_date) + " " + text
- 天氣氣象轉(zhuǎn)換
def parse_html_forecast_code(html):
soup = BeautifulSoup(html, "html.parser")
#獲取建立圖標對應氣象字典,因字典變化較少平夜,抓取一次即可
icon_list_soup = soup.find('div', attrs={'class': 'forecast'}).find_all('div',attrs={'class': 'day'})
for icon in icon_list_soup:
icon_key = icon.find('img')["src"].split("/")[-1]
if (icon_key in icon_list) == False:
icon_list[icon_key] = icon.find('div', attrs={'class': 'wdesc'}).getText().strip()
print(icon_list)
總結(jié)
本輪示例主要實現(xiàn) 嵌套div
數(shù)據(jù)解析(目前嵌套list方案仍需改進)蝶棋,使用 in
關(guān)鍵字對 list
進行重復檢查,利用 enumerate
獲取循環(huán)下標等內(nèi)容忽妒,至此完成氣象預測數(shù)據(jù)抓取......
抓取日志示意