目录
前言
1.安装Selenium
前言
中央气象台网站更新后,以前的爬虫方式就不太能用了,我研究了一下发现主要是因为网站上天气图的翻页模式从点击变成了滑动,页面上的图片src也只显示当前页面的,因此,按照网络通俗的方法去爬取就只能爬出一张图片。看了一些大佬的教程后自己改出来一个代码。
1.安装Selenium
Selenium是一个Web的自动化(测试)工具,它可以根据我们的指令,让浏览器执行自动加载页面,获取需要的数据等操作。pip install selenium

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] #获取文件名#获取图片srcsrc1=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)`
然后就可以轻松的爬取所有图片
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号