• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

python selenium 右键另存为 模拟手动v+自动保存

武飞扬头像
qq_65932616
帮助1

需求

selenium 爬取过程中有部分网址无法图片元素或者无法截图页面,
使用ActionChains点击右键 然后加win32api 模拟手动保存

思路步骤

  1. 导入模块
  2. 在初始化driver对象的时候设定,浏览器静默保存(即保存时不弹出另存为按钮)和默认保存位置
  3. 打开所需网页
  4. 右键图片
  5. win32api 发送v键和enter键

具体代码

from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from seleniumwire import webdriver

from wzs.window import *
from wzs.key import *

chrome_options = webdriver.ChromeOptions()

path = r'C:\Users\Administrator\Desktop'
prefs = {
    'profile.default_content_settings.popups': 0,  # 设置为 0 禁止弹出窗口
    'savefile.default_directory': path,  # 设置保存路径
    'download.default_directory': path  # 设置下载路径
}
chrome_options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.implicitly_wait(10)

driver.get('https://alifei04.cfp.cn/creative/vcg/800/version23/VCG41175510742.jpg')

# 在图片上右键
element = driver.find_element(by=By.XPATH, value='/html/body/img')
action = ActionChains(driver).move_to_element(element)
action.context_click(element).perform()
time.sleep(1)

# 按v
st = time.time()
while True:
    winds = find_handles(class_name='Chrome_WidgetWin_2')
    if winds:
        key_press(winds[0], "v")
        break
    if time.time() - st > 10 * 1000:
        print('没找到保持按钮')
        break

st = time.time()
while True:
    winds = find_handles(title='另存为', class_name='#32770')
    if winds:
        time.sleep(1)
        key_press(winds[0], "return")
        break
    if time.time() - st > 10 * 1000:
        print('没找到另存窗口')
        break

input('*----')  # 可以做其他事情 但是不嫩立即qiut 否则关闭浏览器了后就不能下载了
driver.quit()

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfjjhh
系列文章
更多 icon
同类精品
更多 icon
继续加载