【问题标题】:How do I click enter when a "save-as" window is open with Selenium?当使用 Selenium 打开“另存为”窗口时,如何单击 Enter?
【发布时间】:2019-10-17 11:54:49
【问题描述】:

我想使用 Selenium 保存 this file。我可以使用以下代码单击“另存为”:

driver = webdriver.Chrome(chrome_options=options, executable_path = chrome_driver_path)
driver.get('https://www.shs-conferences.org/articles/shsconf/pdf/2019/06/shsconf_m3e22019_03006.pdf')

ActionChains(driver).move_to_element(driver.find_element_by_xpath('//*[@id="plugin"]')).key_down(Keys.CONTROL).send_keys('s').key_up(Keys.CONTROL).perform()

但是,我无法让 python 在弹出窗口中按下“保存”底部。我试过了:

driver.find_elements_by_xpath("//*[contains(text(), 'Save')]").click()

ActionChains(driver).send_keys(u'\ue007').perform()

有人知道如何点击底部的“保存”吗?

【问题讨论】:

标签: python selenium


【解决方案1】:

更新

虽然如上所述@Glazbee selenium 无法访问操作系统对话框,但pyautogui 有一个解决方法。如果您不想在chrome_optionswebdriver 中设置默认下载文件夹,请尝试以下操作:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pyautogui
import time

driver = webdriver.Chrome(chrome_options=options, executable_path = chrome_driver_path)
driver.get('https://www.shs-conferences.org/articles/shsconf/pdf/2019/06/shsconf_m3e22019_03006.pdf')

webdriver.ActionChains(driver).move_to_element(driver.find_element_by_xpath('//*[@id="plugin"]')).key_down(Keys.CONTROL).send_keys('s').key_up(Keys.CONTROL).perform()
time.sleep(1)
pyautogui.press('enter')

【讨论】:

  • 它不起作用 - 执行代码时没有任何反应
  • @Modvinden 是用来保存文件的弹出窗口吗?
  • 这行不通。 Chrome 不会将保存对话框呈现到页面,而是从本机代码传递。由于 Selenium 无法访问本机二进制文件 - 只是呈现到页面的 Javascript - 它无法访问保存对话框。
  • @Glazbee 你说得对,我之前没明白他想要做什么,我以为他只需要按enter。不过有一个解决方法。
  • 更新后的解决方案能否在无头浏览器上运行?我知道它在路线图上,但我认为它还没有发布
【解决方案2】:

您可以将键盘模块与 selenium 结合使用

import keyboard, time

keyboard.press(['ctrl', 's'])
time.sleep(1)
keyboard.press('enter')

这将让您保存文件。

【讨论】:

    【解决方案3】:

    编辑:据报道此答案已过时。我无法对此进行测试,请考虑使用其他答案中的解决方案。

    这对您不起作用的原因是 Chrome 使用的保存对话框未呈现为网页。这是本机代码。

    要解决这个问题,您可以使用selenium.webdriver.chrome.options.Options 模块。您需要设置一个默认文件目录,否则会出现提示。您可以使用如下脚本; You can find more information here。您也可以在why experimental options are used here上找到信息

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.add_experimental_option("prefs", {
      "download.default_directory": r"C:\Users\xxx\downloads\Test",
      "download.prompt_for_download": False,
      "download.directory_upgrade": True,
      "safebrowsing.enabled": True
    })
    

    【讨论】:

    • 这个不行,弹窗还是出现。
    • @AbhishekRai 对延迟回复表示歉意。我不再使用 Selenium,但截至 2019 年 10 月,这正在工作(不幸的是,我没有版本号)。
    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 2013-08-10
    • 2021-03-28
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    相关资源
    最近更新 更多