我正在使用python-selenium和Chrome 59并试图自动化一个简单的下载序列。当我正常启动浏览器时,下载工作正常,但是当我在无头模式下这样做时,下载不起作用。
# Headless implementation
from selenium import webdriver
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument("headless")
driver = webdriver.Chrome(chrome_options=chromeOptions)
driver.get('https://www.mockaroo.com/')
driver.find_element_by_id('download').click()
# ^^^ Download doesn't start
# Normal Mode
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.mockaroo.com/')
driver.find_element_by_id('download').click()
# ^^^ Download works normally
我甚至尝试过添加默认路径:
prefs = {"download.default_directory" : "/Users/Chetan/Desktop/"}
chromeOptions.add_argument("headless")
chromeOptions.add_experimental_option("prefs",prefs)
添加默认路径在正常实现中有效,但无头版本中仍然存在同样的问题。
如何在无头模式下开始下载?
答案 0 :(得分:39)
是的,这是一个“功能”,为了安全。如前所述,这是错误讨论:https://bugs.chromium.org/p/chromium/issues/detail?id=696481
在Chrome版本62.0.3196.0或更高版本中添加了支持以启用下载。
这是一个python实现。我不得不将命令添加到chromedriver命令。我将尝试提交PR,以便将来包含在库中。
def enable_download_in_headless_chrome(self, driver, download_dir):
# add missing support for chrome "send_command" to selenium webdriver
driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
command_result = driver.execute("send_command", params)
这里有一个小回复来演示如何使用它: https://github.com/shawnbutton/PythonHeadlessChrome
答案 1 :(得分:16)
这是Chrome的一项功能,可防止软件将文件下载到您的计算机。但有一个解决方法。 Read more about it here
你需要做的是通过DevTools启用它,像这样:
async function setDownload () {
const client = await CDP({tab: 'ws://localhost:9222/devtools/browser'});
const info = await client.send('Browser.setDownloadBehavior', {behavior : "allow", downloadPath: "/tmp/"});
await client.close();
}
这是一个人在上述主题中给出的解决方案。 Here is his comment
答案 2 :(得分:7)
这是一个基于Shawn Button's answer的Python实用示例。我已经使用 Chromium 68.0.3440.75 和 chromedriver 2.38
对此进行了测试from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("prefs", {
"download.default_directory": "/path/to/download/dir",
"download.prompt_for_download": False,
})
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': "/path/to/download/dir"}}
command_result = driver.execute("send_command", params)
driver.get('http://download-page.url/')
driver.find_element_by_css_selector("#download_link").click()
答案 3 :(得分:3)
也许你处理的网站会为浏览器返回不同的HTML页面,这意味着你想要的XPath或Id在无头浏览器中可能会有所不同。 尝试在无头浏览器中下载pageSource并将其打开为HTML页面以查看所需的Id或XPath。 您可以将其视为c#示例How to hide FirefoxDriver (using Selenium) without findElement function error in PhantomDriver?。
答案 4 :(得分:3)
更新的 Python 解决方案 - 2021 年 3 月 4 日在 chromedriver v88 和 v89 上测试
这将允许您在无头模式下点击下载文件。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
# Instantiate headless driver
chrome_options = Options()
# Windows path
chromedriver_location = 'C:\\path\\to\\chromedriver_win32\\chromedriver.exe'
# Mac path. May have to allow chromedriver developer in os system prefs
'/Users/path/to/chromedriver'
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_prefs = {"download.default_directory": r"C:\path\to\Downloads"} # (windows)
chrome_options.experimental_options["prefs"] = chrome_prefs
driver = webdriver.Chrome(chromedriver_location,options=chrome_options)
# Download your file
driver.get('https://www.mockaroo.com/')
driver.find_element_by_id('download').click()
答案 5 :(得分:1)
通常看到相同的东西只是用另一种语言编写是多余的,但是因为这个问题使我发疯,所以我希望我能免于痛苦……所以这里是Shawn Button's answer的C#版本(使用无头chrome = 71.0.3578.98,chromedriver = 2.45.615279,平台= Linux 4.9.125-linuxkit x86_64)进行了测试):
var enableDownloadCommandParameters = new Dictionary<string, object>
{
{ "behavior", "allow" },
{ "downloadPath", downloadDirectoryPath }
};
var result = ((OpenQA.Selenium.Chrome.ChromeDriver)driver).ExecuteChromeCommandWithResult("Page.setDownloadBehavior", enableDownloadCommandParameters);
答案 6 :(得分:0)
使用selenium-cucumber-js / selenium-webdriver的JavaScript的完整示例:
const chromedriver = require('chromedriver');
const selenium = require('selenium-webdriver');
const command = require('selenium-webdriver/lib/command');
const chrome = require('selenium-webdriver/chrome');
module.exports = function() {
const chromeOptions = new chrome.Options()
.addArguments('--no-sandbox', '--headless', '--start-maximized', '--ignore-certificate-errors')
.setUserPreferences({
'profile.default_content_settings.popups': 0, // disable download file dialog
'download.default_directory': '/tmp/downloads', // default file download location
"download.prompt_for_download": false,
'download.directory_upgrade': true,
'safebrowsing.enabled': false,
'plugins.always_open_pdf_externally': true,
'plugins.plugins_disabled': ["Chrome PDF Viewer"]
})
.windowSize({width: 1600, height: 1200});
const driver = new selenium.Builder()
.withCapabilities({
browserName: 'chrome',
javascriptEnabled: true,
acceptSslCerts: true,
path: chromedriver.path
})
.setChromeOptions(chromeOptions)
.build();
driver.manage().window().maximize();
driver.getSession()
.then(session => {
const cmd = new command.Command("SEND_COMMAND")
.setParameter("cmd", "Page.setDownloadBehavior")
.setParameter("params", {'behavior': 'allow', 'downloadPath': '/tmp/downloads'});
driver.getExecutor().defineCommand("SEND_COMMAND", "POST", `/session/${session.getId()}/chromium/send_command`);
return driver.execute(cmd);
});
return driver;
};
关键部分是:
driver.getSession()
.then(session => {
const cmd = new command.Command("SEND_COMMAND")
.setParameter("cmd", "Page.setDownloadBehavior")
.setParameter("params", {'behavior': 'allow', 'downloadPath': '/tmp/downloads'});
driver.getExecutor().defineCommand("SEND_COMMAND", "POST", `/session/${session.getId()}/chromium/send_command`);
return driver.execute(cmd);
});
经过测试:
答案 7 :(得分:0)
以下等效于Java,Selenium,chromedriver和chrome v71.x。输入的代码是允许保存下载内容的关键 其他jar:com.fasterxml.jackson.core,com.fasterxml.jackson.annotation,com.fasterxml.jackson.databind
System.setProperty(“ webdriver.chrome.driver”,“ C:\ libraries \ chromedriver.exe”);
String downloadFilepath = "C:\\Download";
HashMap<String, Object> chromePreferences = new HashMap<String, Object>();
chromePreferences.put("profile.default_content_settings.popups", 0);
chromePreferences.put("download.prompt_for_download", "false");
chromePreferences.put("download.default_directory", downloadFilepath);
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary("C:\\pathto\\Chrome SxS\\Application\\chrome.exe");
//ChromeOptions options = new ChromeOptions();
//chromeOptions.setExperimentalOption("prefs", chromePreferences);
chromeOptions.addArguments("start-maximized");
chromeOptions.addArguments("disable-infobars");
//HEADLESS CHROME
**chromeOptions.addArguments("headless");**
chromeOptions.setExperimentalOption("prefs", chromePreferences);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
**ChromeDriverService driverService = ChromeDriverService.createDefaultService();
ChromeDriver driver = new ChromeDriver(driverService, chromeOptions);
Map<String, Object> commandParams = new HashMap<>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map<String, String> params = new HashMap<>();
params.put("behavior", "allow");
params.put("downloadPath", downloadFilepath);
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));**
try {
httpClient.execute(request);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}**
//Continue using the driver for automation
driver.manage().window().maximize();
答案 8 :(得分:0)
我通过使用@Shawn Button共享的解决方法并为
版本:
Chrome版本75.0.3770.100(正式版本)(32位)
ChromeDriver 75.0.3770.90
答案 9 :(得分:0)
使用:google-chrome-stable amd64 86.0.4240.111-1
,chromedriver 86.0.4240.22
,selenium 3.141.0
python 3.8.3
尝试了多种提议的解决方案,但对于无头的chrome并没有真正起作用,我的测试网站也打开了一个新的空白标签,然后下载了数据。
最后放弃了无头程序,并实现了pyvirtualdisplay和xvfd
以模拟X服务器,例如:
from selenium.webdriver.chrome.options import Options # and other imports
import selenium.webdriver as webdriver
import tempfile
url = "https://really_badly_programmed_website.org"
tmp_dir = tempfile.mkdtemp(prefix="hamster_")
driver_path="/usr/bin/chromedriver"
chrome_options = Options()
chrome_options.binary_location = "/usr/bin/google-chrome"
prefs = {'download.default_directory': tmp_dir,}
chrome_options.add_experimental_option("prefs", prefs)
with Display(backend="xvfb",size=(1920,1080),color_depth=24) as disp:
driver = webdriver.Chrome(options=chrome_options, executable_path=driver_path)
driver.get(url)
最后一切正常,并将dowload文件保存在tmp文件夹中。
答案 10 :(得分:0)
我终于通过升级到 Chromium 90 让它工作了!我之前有 72-78 版本,但我看到它最近已修复:https://bugs.chromium.org/p/chromium/issues/detail?id=696481 所以我决定试一试。
所以升级后,花了一段时间(MacOS 中的自制软件太慢了......),我只是做了,没有设置选项或任何东西(这是一个 JavaScript 示例):
await driver.findElement(By.className('download')).click();
它奏效了!我在我一直试图下载的同一个工作文件夹中看到了下载的 PDF...