最简单的selenium+Python自动右键保存图片

[toc]
最近需要爬古籍影印版图片,但是对方网站有反爬虫,于是考虑用selenium,selenium比想象中的简单。右键的难点在于在元素上执行右键之后,selenium就不能操作菜单了。
所以需要别的办法,有的使用autoit第三方软件,比较繁琐;有的用Python的win32库,垃圾;找到了一个非常好的解决方案,用pyautogui库,这个库是对win32的封装,发送按键简单粗暴,比selenium的发送按键还要人性化,点赞。代码如下。
安装pyautogui

pip install autogui

代码如下

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import pyautogui
from time import sleep
# 代码的健壮性

driver = webdriver.Chrome('d:/coding/chromedriver.exe')  # Optional argument, if not specified will search path.
driver.get('https://www.jianshu.com/');
# 选择元素
wait = WebDriverWait(driver,10)
# 右键单击图片
img = wait.until(EC.element_to_be_clickable((By.TAG_NAME,'img')))
# 执行鼠标动作
actions = ActionChains(driver)
# 找到图片后右键单击图片
actions.context_click(img)
actions.perform()
# 发送键盘按键,根据不同的网页,
# 右键之后按对应次数向下键,
# 找到图片另存为菜单
pyautogui.typewrite(['down','down','down','down','down','down','down','enter','enter'])
# 单击图片另存之后等1s敲回车
sleep(1)
pyautogui.typewrite(['enter'])
按7次向下键找到图片另存为选项

敲回车保存图片

整个过程都是程序自动运行,这个就构成了自动下载图片的基础。

你可能感兴趣的:(最简单的selenium+Python自动右键保存图片)