python爬取氣象臺每日天氣圖代碼
前言
中央氣象臺網站更新后,以前的爬蟲方式就不太能用了,我研究了一下發(fā)現主要是因為網站上天氣圖的翻頁模式從點擊變成了滑動,頁面上的圖片src也只顯示當前頁面的,因此,按照網絡通俗的方法去爬取就只能爬出一張圖片??戳艘恍┐罄械慕坛毯笞约焊某鰜硪粋€代碼。
1.安裝Selenium
Selenium是一個Web的自動化(測試)工具,它可以根據我們的指令,讓瀏覽器執(zhí)行自動加載頁面,獲取需要的數據等操作。
pip install selenium
2. 安裝chromedriver
Selenium 自身并不具備瀏覽器的功能,Google的Chrome瀏覽器能方便的支持此項功能,需安裝其驅動程序Chromedriver
下載地址:http://chromedriver.storage.googleapis.com/index.html
在google瀏覽器的地址欄輸入‘chrome://version/’,可以查看版本信息,下載接近版本的就可以。
3.代碼
從圖里可以看到,向前翻頁指令對應的id是'prev'

from selenium import webdriver ## 導入selenium的瀏覽器驅動接口
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
import time
import os
import urllib.request
level=['地面','925hPa','850hPa','700hPa','500hPa','100hPa']
chrome_driver = '路徑/chromedriver.exe' #chromedriver的文件位置
driver = webdriver.Chrome(executable_path = chrome_driver) #加載瀏覽器驅動
driver.get('http://www.nmc.cn/publish/observations/china/dm/weatherchart-h000.htm') #打開頁面
time.sleep(1)
#模擬鼠標選擇高度層
for z in level:
button1=driver.find_element_by_link_text(z) #通過link文字精確定位元素
action = ActionChains(driver).move_to_element(button1) #鼠標懸停在一個元素上
action.click(button1).perform() #鼠標單擊
time.sleep(1)
for p in range(0,6): #下載最近6個時次的天氣圖
str_p=str(p)
#模擬鼠標選擇時間
button2=driver.find_element_by_id('prev') #通過id精確定位元素
action = ActionChains(driver).move_to_element(button2) #鼠標懸停在一個元素上
action.click(button2).perform() #鼠標單擊
time.sleep(1)
#模擬鼠標選擇圖片
elem_pic = driver.find_element_by_id('imgpath') #通過id精確定位元素
action = ActionChains(driver).move_to_element(elem_pic)
#action.context_click(elem_pic).perform() #鼠標右擊
filename= str(elem_pic.get_attribute('src')).split('/')[-1].split('?')[0] #獲取文件名
#獲取圖片src
src1=elem_pic.get_attribute('src')
if os.path.exists('存圖路徑/'+z+'') is not True :
os.makedirs('存圖路徑/'+z+'')
urllib.request.urlretrieve(src1 , '存圖路徑/'+z+'/'+filename)
print(filename)
time.sleep(1)然后就可以輕松的爬取所有圖片

到此這篇關于python爬取氣象臺每日天氣圖代碼的文章就介紹到這了,更多相關python爬取天氣圖內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解如何使用Python的Plotly庫進行交互式圖形可視化
Python中有許多強大的工具和庫可用于創(chuàng)建交互式圖形,其中之一就是Plotly庫,Plotly庫提供了豐富的功能和靈活的接口,使得創(chuàng)建各種類型的交互式圖形變得簡單而直觀,本文將介紹如何使用Plotly庫來創(chuàng)建交互式圖形,需要的朋友可以參考下2024-05-05
Python中用psycopg2模塊操作PostgreSQL方法
python可以操作多種數據庫,本篇文章給大家介紹了用psycopg2模塊操作PostgreSQL方法,一起來學習下。2017-11-11

