我下载了最新版本的铬,以测试无头功能。
当我跑(作为根,因为我还在测试东西):
./chrome --no-sandbox http://cp7.awardspace.com/speed-test/awardspace-data1mb.zip
在GUI终端中,它打开Chromium并下载文件。
如果我试图无头地运行它,我输入以下内容:
./chrome --no-sandbox --headless http://cp7.awardspace.com/speed-test/awardspace-data1mb.zip
终端输出一些信息,没有窗口打开,但是:我没有在任何地方下载文件。
我一直在寻找互联网和讨论组以获取更多信息,但找不到任何东西。
文件下载是否在Chromium的无头模式下工作?
在Java中使用以下代码:
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", "//home//vaibhav//Desktop");
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.seleniumhq.org/download/");
driver.findElement(By.linkText("32 bit Windows IE")).click();
注意:不完全回答问题,但解决了问题
我研究了很多关于使用不同的参数/选项/偏好进行无头镀铬下载,但没有任何效果。然后我使用Apache Commons的FileUtils使用标准的Java方式下载文件
FileUtils.copyURLToFile(URI, FILE);
借助Chrome Remote Interface,我能够使用chrome headless下载文件
public void TryEnableFileDownloading(string downloadPath)
{
TrySendCommand("Page.setDownloadBehavior", new Dictionary<string, object>()
{
["behavior"] = "allow",
["downloadPath"] = downloadPath
});
}
可以在此处找到与selenium集成的完整代码
https://github.com/cezarypiatek/Tellurium/blob/master/Src/MvcPages/SeleniumUtils/ChromeRemoteInterface/ChromeRemoteInterface.cs
有关setDownloadBehavior和Chrome Remote界面的更多信息
https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-setDownloadBehavior