Python练习程序员

02_中央气象台

2017-03-10  本文已影响50人  过桥

简述

最近发现气象数据很适合进行Python分步完成抓取练习,检索各类资源对比发现中央气象台数据相对完整,类型也较为丰富,故计划针对不同类型分别练习。抓取数据请勿存档,商用请联系官方

爬取对象

抓取中央气象台卫星云图

使用包

import time, os #定时抓取
import requests 
from bs4 import BeautifulSoup
import datetime #精确时间

实现步骤

1、抓取对象分析
2、抓取与本地保存核心代码
    for image_li in list_soup.find_all('li'):
        image_name = image_li.find('p', attrs={'class': 'time'}).getText().replace(':','_')
        img_small = image_li.find('p', attrs={'class': 'img'}).find('img')["data-original"] #小图
img_localhost = folder + '\\' + image_name + '.jpg'
img_req = requests.get(img_small, timeout=20)
with open(img_localhost, 'wb') as f:
        f.write(img_req.content)
3、优化
http://image.nmc.cn/product/2017/03/10/WXCL/small/SEVP_NSMC_WXCL_ASC_E99_ACHN_LNO_PY_20170310081500000.JPG?v=1489134787788
http://image.nmc.cn/product/2017/03/10/WXCL/SEVP_NSMC_WXCL_ASC_E99_ACHN_LNO_PY_20170310081500000.JPG?v=1489134788000
img_small = image_li.find('p', attrs={'class': 'img'}).find('img')["data-original"] #小图
img_big = img_small.replace('small/','')
def re_exe(cmd, inc = 60): 
    while True: 
        os.system(cmd);
        main()
        time.sleep(inc) 

# N秒 执行一次
re_exe("echo %time%", 1800)
    if os.path.exists(folder) == False:
        os.makedirs(folder)

    #如果文件不存在,且大小不为 0 字节,开始下载另存
    if os.path.isfile(img_localhost) == False or os.path.getsize(img_localhost) == 0:
#下载清单
DOWNLOAD_URL = [("能见度","seaplatform1","http://www.nmc.cn/publish/sea/seaplatform1.html"),("风","hourly-winds","http://www.nmc.cn/publish/observations/hourly-winds.html"),("气温","hourly-temperature","http://www.nmc.cn/publish/observations/hourly-temperature.html"),("小时降雨量","hourly-precipitation","http://www.nmc.cn/publish/observations/hourly-precipitation.html"),("卫星云图","fy2", "http://www.nmc.cn/publish/satellite/fy2.htm")]

    for title, folder, url in DOWNLOAD_URL:
        #print(title, folder, url)
        html = download_page(url)

总结

本轮示例主要复习了图片抓取,完善文件夹、文件处理,针对动态(更新较为频繁)网站设置自动抓取任务,完成后感觉本地连播此类图片还是挺有意思的......
完整代码

Paste_Image.png
上一篇 下一篇

猜你喜欢

热点阅读