python爬取氣象臺每日天氣圖代碼
中央氣象臺網(wǎng)站更新后,以前的爬蟲方式就不太能用了,我研究了一下發(fā)現(xiàn)主要是因?yàn)榫W(wǎng)站上天氣圖的翻頁模式從點(diǎn)擊變成了滑動,頁面上的圖片src也只顯示當(dāng)前頁面的,因此,按照網(wǎng)絡(luò)通俗的方法去爬取就只能爬出一張圖片??戳艘恍┐罄械慕坛毯笞约焊某鰜硪粋€代碼。
1.安裝Selenium
Selenium是一個Web的自動化(測試)工具,它可以根據(jù)我們的指令,讓瀏覽器執(zhí)行自動加載頁面,獲取需要的數(shù)據(jù)等操作。
pip install selenium
2. 安裝chromedriver
Selenium 自身并不具備瀏覽器的功能,Google的Chrome瀏覽器能方便的支持此項(xiàng)功能,需安裝其驅(qū)動程序Chromedriver
下載地址:http://chromedriver.storage.googleapis.com/index.html
在google瀏覽器的地址欄輸入‘chrome://version/’,可以查看版本信息,下載接近版本的就可以。
3.代碼
從圖里可以看到,向前翻頁指令對應(yīng)的id是'prev'
from selenium import webdriver ## 導(dǎo)入selenium的瀏覽器驅(qū)動接口 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) #加載瀏覽器驅(qū)動 driver.get('http://www.nmc.cn/publish/observations/china/dm/weatherchart-h000.htm') #打開頁面 time.sleep(1) #模擬鼠標(biāo)選擇高度層 for z in level: button1=driver.find_element_by_link_text(z) #通過link文字精確定位元素 action = ActionChains(driver).move_to_element(button1) #鼠標(biāo)懸停在一個元素上 action.click(button1).perform()#鼠標(biāo)單擊 time.sleep(1) for p in range(0,6): #下載最近6個時次的天氣圖 str_p=str(p) #模擬鼠標(biāo)選擇時間 button2=driver.find_element_by_id('prev') #通過id精確定位元素 action = ActionChains(driver).move_to_element(button2) #鼠標(biāo)懸停在一個元素上 action.click(button2).perform()#鼠標(biāo)單擊 time.sleep(1) #模擬鼠標(biāo)選擇圖片 elem_pic = driver.find_element_by_id('imgpath') #通過id精確定位元素 action = ActionChains(driver).move_to_element(elem_pic) #action.context_click(elem_pic).perform() #鼠標(biāo)右擊 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)
然后就可以輕松的爬取所有圖片
到此這篇關(guān)于python爬取氣象臺每日天氣圖代碼的文章就介紹到這了,更多相關(guān)python爬取天氣圖內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。