【问题标题】:Automatically download files using selenium Chromedriver 3.11.0 on a Mac在 Mac 上使用 selenium Chromedriver 3.11.0 自动下载文件
【发布时间】:2018-09-30 12:42:10
【问题描述】:

我在这里阅读了一堆硒主题,并且一直在讨论如何为 chromedriver 设置权限/选项。我编写了以下代码:

System.setProperty("webdriver.chrome.driver", "/Users/username/chromedriver");
String downloadFilepath = "//User//username//automation-testing//";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
options.addArguments("disable-popup-blocking");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);

对下载页面的调用是使用一个简单的

driver.get(url); 

重定向到 csv 文件。

我不断收到一个弹出提示,询问我是否可以下载文件。值得一提的是,新的 ChromeDriver(cap) 行已被弃用,但我似乎找不到有关如何使用涵盖此用例的替代方法的文档。

【问题讨论】:

  • 只需new ChromeDriver(options);

标签: java selenium selenium-webdriver selenium-chromedriver mutablecapabilities


【解决方案1】:

看来你快到了。您需要使用 MutableCapabilities 类中的方法 merge()DesiredCapabilities 类型的对象合并到 ChromeOptions 类型的对象中并启动 WebDriverWebClient 实例通过传递 ChromeOptions 对象如下:

System.setProperty("webdriver.chrome.driver", "/Users/username/chromedriver");
String downloadFilepath = "//User//username//automation-testing//";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
options.addArguments("disable-popup-blocking");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
options.merge(cap);
WebDriver driver = new ChromeDriver(options);

PS:作为参考,您可以查看mutablecapabilities标签中的讨论


更新

根据您的评论更新,当您遇到下载确认窗口时,您可以查看讨论 Auto-download in firefox browser with java-selenium not working 来解决您的问题。

【讨论】:

  • 奇怪的是,即使在进行了这些更改之后,当我运行它时,我仍然会收到一个确认窗口——你知道为什么吗?
  • @A_Elric 我的答案是根据您的基线问题It's worth mentioning that the new ChromeDriver(cap) line is deprecated, but I can't seem to find documentation on how to use the method that replaced it that covers this use case. 构建的。如果您的要求发生了变化,请随时提出新票。 Satckoverflow 志愿者将很乐意为您提供帮助。
  • 问题是由于弹出窗口导致下载未发生-尽管提到这可能部分是因为我没有使用可变功能标签-在更改标签后,我仍然被阻止更大的问题。不过,我很高兴为您的努力投票。
  • @A_Elric 查看我的答案更新并让我知道状态。
  • 我不确定该解决方案是否适用于 chrome,因为参数可能不同...
【解决方案2】:

我使用的解决方案是下面的完整源代码,通过下面的 google 登录 jira,然后将过滤视图下载到下面的 csv(当前选择):

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class Scrape {
    public static void doScrape(String[] urls) {
        try{
            for(String url : urls) {
                //Create new Chromedriver, set file download path, allow the download popup to be automatically accepted,and merge the properties into chromedriver
                System.setProperty("webdriver.chrome.driver", "/Users/damienbell/chromedriver");
                String downloadFilepath = "/Users/damienbell/automation-testing";

                ChromeOptions options = new ChromeOptions();
                options.addArguments("--test-type");
                //options.addArguments("--headless");
                options.addArguments("--disable-extensions");

                //Instantiate above options in driverService
                ChromeDriverService driverService = ChromeDriverService.createDefaultService();
                ChromeDriver driver = new ChromeDriver(driverService, options);


                Map<String, Object> commandParams = new HashMap<>();
                commandParams.put("cmd", "Page.setDownloadBehavior");

                Map<String, Object> params = new HashMap<String, Object>();
                params.put("behavior", "allow");
                params.put("downloadPath", downloadFilepath);
                params.put("cmd", "Page.setDownloadBehavior");


                commandParams.put("params", params);
                ObjectMapper om = new ObjectMapper();
                CloseableHttpClient httpClient = HttpClients.createDefault();
                String command = null;
                try{
                    command = om.writeValueAsString(commandParams);
                }catch(JsonProcessingException jpe){ jpe.printStackTrace(); }
                String postURL = driverService.getUrl().toString() + "/session/" + driver.getSessionId() + "/chromium/send_command";
                HttpPost postRequest = new HttpPost(postURL);
                postRequest.addHeader("content-type", "application/json");
                postRequest.addHeader("accept", "*.*");
                try{
                    postRequest.setEntity(new StringEntity(command));
                    httpClient.execute(postRequest);
                }
                catch (UnsupportedEncodingException uee) { uee.printStackTrace(); }
                catch (IOException ioe) { ioe.printStackTrace(); }


                driver.get("https://x.atlassian.net/secure/Dashboard.jspa?selectPageId=11502");
                Thread.sleep(3000);  // Let the user actually see something!
                ((ChromeDriver) driver).findElementById("menu-sign-in").click();
                Thread.sleep(3000);
                ((ChromeDriver) driver).findElementById("google-signin-button").click();
                Thread.sleep(3000);
                ((ChromeDriver) driver).findElementById("identifierId").sendKeys("email@email.com");
                Thread.sleep(700);
                ((ChromeDriver) driver).findElementById("identifierNext").click();
                Thread.sleep(2000);
                driver.findElement(By.cssSelector("input[name=password]")).sendKeys(Secret.getPassword());
                Thread.sleep(600);
                ((ChromeDriver) driver).findElementById("passwordNext").click();
                Thread.sleep(10000);
                driver.get(url);
                Thread.sleep(56000);
                File[] files = new File("/Users/user/automation-testing").listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File path) {
                        if (path.isFile()) {
                            ParseCSV.doParse(path);
                            path.delete();
                            return true;
                        }
                        else{
                            System.out.println("Failure");
                        }
                        return false;
                    }
                });
                driver.quit();
            }
        }catch( java.lang.InterruptedException inter ){ System.err.println("Thread.sleep broke something, wtf"); inter.printStackTrace(); }
    }
}

【讨论】:

    【解决方案3】:

    在 python 的 selenium 库中,我已将“headless”参数添加到 webdriver.ChromeOptions() 对象,因此它不会显示 chrome 窗口 - 意味着没有下载提示。

    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('headless')
    

    【讨论】:

      猜你喜欢
      • 2015-01-09
      • 2021-11-16
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 2019-11-08
      • 2022-01-06
      • 1970-01-01
      相关资源
      最近更新 更多