无法使用selenium下载任何文件

时间:2018-04-10 12:19:38

标签: java selenium selenium-webdriver headless google-chrome-headless

我想使用selenium下载一个文件。由于幻影js和chrome无头没有supoort下载所以我尝试了以下的东西。但是当我在普通的chrome中使用这个代码的问题它说道路太长而且没有下载文件。如何在chrome和headlesss中下载文件

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

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Downjar {

    public static void main(String[] args) throws ClientProtocolException, IOException {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        ChromeOptions options = new ChromeOptions();
              options.addArguments("--test-type");
              //options.addArguments("--headless");
               options.addArguments("--disable-extensions"); //to disable browser extension popup

               ChromeDriverService driverService = ChromeDriverService.createDefaultService();
               ChromeDriver driver = new ChromeDriver(driverService, options);

               Map<String, Object> commandParams = new HashMap<>();
               commandParams.put("cmd", "Page.setDownloadBehavior");
               Map<String, String> params = new HashMap<>();
               params.put("behavior", "allow");
               params.put("downloadPath", "C://Users//poltu//Downloads//");
               commandParams.put("params", params);
               ObjectMapper objectMapper = new ObjectMapper();
               HttpClient httpClient = HttpClientBuilder.create().build();
               String command = objectMapper.writeValueAsString(commandParams);
               String u = driverService.getUrl().toString() + "/session/" + driver.getSessionId() + "/chromium/send_command";
               HttpPost request = new HttpPost(u);
               request.addHeader("content-type", "application/json");
               request.setEntity(new StringEntity(command));
               httpClient.execute(request);
         driver.get("http://www.java2s.com/Code/Jar/j/Downloadjacksonannotations212jar.htm");          
            driver.findElement(By.xpath("html/body/div/div/div[2]/p[2]/a")).click();

    }

}

1 个答案:

答案 0 :(得分:2)

您必须在下载路径中使用反斜杠。

尝试

params.put("downloadPath", "C:\\Users\\poltu\\Downloads\\");

希望有所帮助