【问题标题】:How to download .docx file using Selenium webdriver in Java?如何在 Java 中使用 Selenium webdriver 下载 .docx 文件?
【发布时间】:2015-04-21 11:13:51
【问题描述】:

谁能告诉我如何使用 selenium(java) 下载 word 文件?我下面的代码不起作用。

FirefoxProfile prof = new FirefoxProfile();
prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/word");

当我点击页面中的“下载链接或图标”时,它会提示一个弹出窗口保存下载文件(见下图),我需要点击弹出窗口中的OK 按钮。

请告诉我如何使用 Firefox 执行此操作。

【问题讨论】:

    标签: java selenium selenium-webdriver popup popupwindow


    【解决方案1】:

    试试这个

    import java.awt.Robot;
    

    并使用

    Robot r = new Robot();
    r.keyPress(KeyEvent.VK_ENTER);
    r.keyRelease(KeyEvent.VK_ENTER);
    

    这将以编程方式按 Enter。

    【讨论】:

      【解决方案2】:

      您需要使用 ROBOT 类来触发 ENTER 操作事件。在 java 中,如果您想触发任何事件,您必须使用 Robot 类以编程方式键入或触发事件,如 ENTER 和 ESCAPE。

      // Create object of Robot class
      Robot object=new Robot();
      
      // Press Enter
      object.keyPress(KeyEvent.VK_ENTER);
      
      // Release Enter
      object.keyRelease(KeyEvent.VK_ENTER);
      

      有关这方面的信息,您可以使用link

      【讨论】:

      • 只有在本地机器上运行时才会起作用,机器人类在连接到远程浏览器(例如 selenium gird、sauce labs 等)时将不起作用,因为您只是在本地控制光标机器。一般来说,这是一个非常糟糕且不可靠的想法。
      【解决方案3】:

      使用以下设置让它工作:

      FirefoxOptions options = new FirefoxOptions();
      FirefoxProfile profile = new FirefoxProfile();
      profile.setPreference("browser.download.folderList", 2);
      profile.setPreference("browser.download.dir", "C:\\Windows\\temp");
      profile.setPreference("browser.download.useDownloadDir", true);
      profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
      options.setProfile(profile);
      driver = new FirefoxDriver(options);
      

      更多关于偏好设置的信息可以在这里找到:http://toolsqa.com/selenium-webdriver/how-to-download-files-using-selenium/

      【讨论】:

        猜你喜欢
        • 2012-06-03
        • 1970-01-01
        • 2017-08-26
        • 2018-04-14
        • 1970-01-01
        • 2018-04-06
        • 2013-10-24
        • 2018-07-08
        相关资源
        最近更新 更多