python 保存图片代码_最简单的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次向下鍵找到圖片另存為選項
敲回車保存圖片
整個過程都是程序自動運行,這個就構成了自動下載圖片的基礎。
總結
以上是生活随笔為你收集整理的python 保存图片代码_最简单的selenium+Python自动右键保存图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 将两幅图拼接_清华王教授典
- 下一篇: linux 多个select,Linux