今天就跟大家聊聊有關python怎么爬取氣象臺每日天氣圖代碼,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
中央氣象臺網站更新后,以前的爬蟲方式就不太能用了,我研究了一下發現主要是因為網站上天氣圖的翻頁模式從點擊變成了滑動,頁面上的圖片src也只顯示當前頁面的,因此,按照網絡通俗的方法去爬取就只能爬出一張圖片??戳艘恍┐罄械慕坛毯笞约焊某鰜硪粋€代碼。
Selenium是一個Web的自動化(測試)工具,它可以根據我們的指令,讓瀏覽器執行自動加載頁面,獲取需要的數據等操作。
pip install selenium
Selenium 自身并不具備瀏覽器的功能,Google的Chrome瀏覽器能方便的支持此項功能,需安裝其驅動程序Chromedriver
下載地址:http://chromedriver.storage.googleapis.com/index.html
在google瀏覽器的地址欄輸入‘chrome://version/’,可以查看版本信息,下載接近版本的就可以。
從圖里可以看到,向前翻頁指令對應的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怎么爬取氣象臺每日天氣圖代碼有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。