python爬取氣象臺每日天氣圖代碼
中央氣象臺網(wǎng)站更新后,以前的爬蟲方式就不太能用了,我研究了一下發(fā)現(xiàn)主要是因為網(wǎng)站上天氣圖的翻頁模式從點擊變成了滑動,頁面上的圖片src也只顯示當前頁面的,因此,按照網(wǎng)絡通俗的方法去爬取就只能爬出一張圖片??戳艘恍┐罄械慕坛毯笞约焊某鰜硪粋€代碼。
1.安裝Selenium
Selenium是一個Web的自動化(測試)工具,它可以根據(jù)我們的指令,讓瀏覽器執(zhí)行自動加載頁面,獲取需要的數(shù)據(jù)等操作。
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ù)瀏覽下面的相關文章希望大家以后多多支持本站!
版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。
關注官方微信