Test work properly on Chrome, not on Firefox - selenium

I wrote test using TestNG and selenium.
code...
actions.sendKeys(Keys.chord(Keys.CONTROL, "a"));
actions.sendKeys(Keys.BACK_SPACE);
actions.build().perform();
code...
I wanted to delete text in login window using these sendKeys, with DataProvider
#DataProvider(name = "inputs")
public Object[][] getData() {
return new Object[][]{
{"000000000", true},
{"000000000", true}
};
}
Html:
<div><input type="tel" class="valid TextInput-kJdagG iVdKHC" name="recoveryPhone" id="eb69ff0b-3427-6986-7556-b7af40ffb156" aria-describedby="eb69ff0b-3427-6986-7556-b7af40ffb156" value="+48 "></div>
Error message:
Unable to read VR
Path1523545392670 Marionette INFO Enabled via --marionette
1523545393744 Marionette INFO Listening on port 52644
1523545394180 Marionette WARN TLS certificate errors will be ignored for this session
Test work as I expected on Chrome, but on firefox these sendKeys not always mark the text, and clear this text. In project I have to use action class. Why the test runs differently?

Check this post https://github.com/mozilla/geckodriver/issues/665 against your versions (browser, browser driver, selenium etc which are always sensible to include in any question), it could be a known bug with the geckodriver.
The post includes a work around of creating the chord in a different way, using:
List<CharSequence> keyWithModifiers = new ArrayList<CharSequence>();
keyWithModifiers.add(Keys.CONTROL);
keyWithModifiers.add("a");
String ctrlA = Keys.chord(keyWithModifiers);
textFieldElem.sendKeys(ctrlA);
This approach worked for me using Selenium 3.7.1 Java bindings, gecko driver 0.18.0 (64 bit) and Firefox 57.0.2 - 59.0

Related

Download file through Google Chrome RemoteWebDriver- headless mode in Linux using Selenium Java [duplicate]

I'm do me code in Cromedrive in 'normal' mode and works fine. When I change to headless mode it don't download the file. I already try the code I found alround internet, but didn't work.
chrome_options = Options()
chrome_options.add_argument("--headless")
self.driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=r'{}/chromedriver'.format(os.getcwd()))
self.driver.set_window_size(1024, 768)
self.driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': os.getcwd()}}
self.driver.execute("send_command", params)
Anyone have any idea about how solve this problem?
PS: I don't need to use Chomedrive necessarily. If it works in another drive it's fine for me.
First the solution
Minimum Prerequisites:
Selenium client version: Selenium v3.141.59
Chrome version: Chrome v77.0
ChromeDriver version: ChromeDriver v77.0
To download the file clicking on the element with text as Download Data within this website you can use the following solution:
Code Block:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless")
options.add_argument("--window-size=1920,1080")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe', service_args=["--log-path=./Logs/DubiousDan.log"])
print ("Headless Chrome Initialized")
params = {'behavior': 'allow', 'downloadPath': r'C:\Users\Debanjan.B\Downloads'}
driver.execute_cdp_cmd('Page.setDownloadBehavior', params)
driver.get("https://www.mockaroo.com/")
driver.execute_script("scroll(0, 250)");
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#download"))).click()
print ("Download button clicked")
#driver.quit()
Console Output:
Headless Chrome Initialized
Download button clicked
File Downloading snapshot:
Details
Downloading files through Headless Chromium was one of the most sought functionality since Headless Chrome was introduced.
Since then there were different work-arounds published by different contributors and some of them are:
Downloading with chrome headless and selenium
Python equivalent of a given wget command
Now the, the good news is Chromium team have officially announced the arrival of the functionality Downloading file through Headless Chromium.
In the discussion Headless mode doesn't save file downloads #eseckler mentioned:
Downloads in headless work a little differently. There's the Page.setDownloadBehavior devtools command to set a download folder. We're working on a way to use DevTools network interception to stream the downloaded file via DevTools as well.
A detailed discussion can be found at Issue 696481: Headless mode doesn't save file downloads
Finally, #bugdroid revision seems to have nailed the issue for us.
[ChromeDriver] Added support for headless mode to download files
Previously, Chromedriver running in headless mode would not properly download files due to the fact it sparsely parses the preference file given to it. Engineers from the headless chrome team recommended using DevTools's "Page.setDownloadBehavior" to fix this. This changelist implements this fix. Downloaded files default to the current directory and can be set using download_dir when instantiating a chromedriver instance. Also added tests to ensure proper download functionality.
Here is the revision and commit
From ChromeDriver v77.0.3865.40 (2019-08-20) release notes:
Resolved issue 2454: Headless mode doesn't save file downloads [Pri-2]
Solution
Update ChromeDriver to latest ChromeDriver v77.0 level.
Update Chrome to Chrome Version 77.0 level. (as per ChromeDriver v76.0 release notes)
Note: Chrome v77.0 is yet to be GAed/pushed for release so till then you can download and install a development build and test either from:
Chrome Canary
Latest build from the Dev Channel
Outro
However Mac OSX users have a wait for their pie as On Chromedriver, headless chrome crashes after sending Page.setDownloadBehavior on MacOSX.
Chomedriver Version: 95.0.4638.54
Chrome Version 95.0.4638.69
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless")
options.add_argument("--start-maximized")
options.add_argument("--no-sandbox")
options.add_argument("--disable-extensions")
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--disable-gpu")
options.add_argument('--disable-software-rasterizer')
options.add_argument("user-agent=Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166")
options.add_argument("--disable-notifications")
options.add_experimental_option("prefs", {
"download.default_directory": "C:\\link\\to\\folder",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing_for_trusted_sources_enabled": False,
"safebrowsing.enabled": False
}
)
What seemed to work was that I used "\\" instead of "/" for the address. The latter approach didn't throw any error, but didn't download any documents either. But, using double back slashes did the job.
For javascript use below code:
const chrome = require('selenium-webdriver/chrome');
let options = new chrome.Options();
options.addArguments('--headless --window-size=1500,1200');
options.setUserPreferences({ 'plugins.always_open_pdf_externally': true,
"profile.default_content_settings.popups": 0,
"download.default_directory": Download_File_Path });
driver = await new webdriver.Builder().setChromeOptions(options).forBrowser('chrome').build();
Then switch tabs as soon as you click the download button:
await driver.sleep(1000);
var Handle = await driver.getAllWindowHandles();
await driver.switchTo().window(Handle[1]);
This C# works for me
Note the new headless option https://www.selenium.dev/blog/2023/headless-is-going-away/
private IWebDriver StartBrowserChromeHeadlessDriver()
{
var chromeOptions = new ChromeOptions();
chromeOptions.AddArgument("--headless=new");
chromeOptions.AddArgument("--window-size=1920,1080");
chromeOptions.AddUserProfilePreference("download.default_directory", downloadFolder);
var chromeDownload = new Dictionary<string, object>
{
{ "behavior", "allow" },
{ "downloadPath", downloadFolder }
};
var driver = new ChromeDriver(driverFolder, chromeOptions, TimeSpan.FromSeconds(timeoutSecs));
driver.ExecuteCdpCommand("Browser.setDownloadBehavior", chromeDownload);
return driver;
}
import pathlib
from selenium.webdriver import Chrome
driver = Chrome()
driver.execute_cdp_cmd("Page.setDownloadBehavior", {
"behavior": "allow",
"downloadPath": str(pathlib.Path.home().joinpath("Downloads"))
})
I don't think you should be using the browser for downloading content, leave it to Chrome developers/testers.
I believe you should rather get href attribute of the element you want to download and obtain it using requests library
If your site requires authentication you could fetch cookies from the browser instance and pass them to requests.Session.

Selenium commands not working in Chrome web driver (working with firefox)

I'm writing integration/e2e tests and for some reason any selenium driver commands don't see to be working with chromedriver, but they are working flawlessly with firefox driver and the firefox headless driver.
Commands tried: moveByOffset, and doubleClick
Tried both Geb's Interact method
interact {
doubleClick(centerClickable)
}
and accessing the webdriver directly:
def driver = browser.getDriver()
Actions action = new Actions(driver)
WebElement element= driver.findElement(By.className("vis-drag-center"))
def doubleclick = action.doubleClick(element).build()
doubleclick.perform()
Both methods work with the firefox driver. Neither work with chrome driver.
GebConfig.groovy file is set up as thus:
import io.github.bonigarcia.wdm.WebDriverManager
import org.openqa.selenium.Dimension
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
import org.openqa.selenium.firefox.FirefoxDriver
import org.openqa.selenium.firefox.FirefoxOptions
def chromeWebDriverVersion = '70.0.3538.67'
def driverFirefox = {
WebDriverManager.firefoxdriver().setup()
def driver = new FirefoxDriver()
driver.manage().window().setSize(new Dimension(width, height))
return driver
}
// ChromeDriver reference: https://sites.google.com/a/chromium.org/chromedriver/
// Download and configure ChromeDriver using https://github.com/bonigarcia/webdrivermanager
def driverChrome = {
WebDriverManager.chromedriver().version(chromeWebDriverVersion).setup()
def driver = new ChromeDriver()
driver.manage().window().setSize(new Dimension(width, height))
return driver
}
environments {
firefox {
driver = driverFirefox
}
chrome {
driver = driverChrome
}
//driver = driverFirefox
driver = driverChrome
I also tried version 2.43 of chrome.
Additional information:
Mac Mojave
Selenium v 3.7.0
geb v 2.2
spockcore v 1.1-groovy-2.4
groovy v 2.4.5
webdrivermanager v 3.0.0
If anyone is interested, what the test is doing: Selecting a vis.js element by clicking on it. Sleeping for a second (code not included here), then opening/activating it by double clicking it. Or dragging it.
Apart from the selenium actions everything works fine with chromedriver and geb. It's only now that I need the doubleClick and moveByOffset (not move to an element!) that I'm getting issues getting things to work properly
I found a similar question on here, might be the same issue. Maybe not. But there's no solution provided: Selenium Web Driver DragAndDropToOffset in Chrome not working?
Any help is hugely appreciated.
Thank you for your response kriegaex.
Your tests work for me as well. This leads me to think there's just some lower-level interaction between differences in how selenium's chromedriver and firefox driver have implemented the doubleclick and dragAndDropBy actions + the way our application responds to commands.
For any other people observing similar behaviour, I use a work-around where I add an additional action for chromedriver. Perhaps it's nicer to actually find out which KEYDOWN events etc. you should be using and fire those, or perhaps find out why application isn't responding to these events. But I feel like enough time is spent on this already :)
if (browser.getDriver().toString().contains("chrome")) {
// Work-around for chromedriver's double-click implementation
content.click()
}
interact {
doubleClick(content)
}
And for the dragAndDropBy:
def drag(Navigator content, int xOff, int yOff) {
//Work-around: move additional time for when chrome driver is used.
int timesToMove = browser.getDriver().toString().contains("chrome") ? 2 : 1
interact {
clickAndHold(content)
timesToMove.times {
moveByOffset(xOff, yOff)
}
release()
}
}
I just had a little bit of time and was curious because I never tried to perform a double-click in any of my tests before. So I used this page as a test case and ran the following test with both Firefox and Chrome drivers:
package de.scrum_master.stackoverflow
import geb.spock.GebReportingSpec
import org.openqa.selenium.By
import org.openqa.selenium.interactions.Actions
class DoubleClickTest extends GebReportingSpec {
def "double-click via Geb interaction"() {
given:
go "https://demo.guru99.com/test/simple_context_menu.html"
def doubleClickButton = $("button", text: "Double-Click Me To See Alert")
expect:
withAlert {
interact {
doubleClick(doubleClickButton)
}
} == "You double clicked me.. Thank You.."
}
def "double-click via Selenium action"() {
given:
go "https://demo.guru99.com/test/simple_context_menu.html"
def doubleClickButton = driver.findElement(By.tagName("button"))
def doubleClick = new Actions(driver).doubleClick(doubleClickButton).build()
expect:
withAlert {
doubleClick.perform()
} == "You double clicked me.. Thank You.."
}
}
It works flawlessly, both ways of double-clicking trigger the expected Javascript alert.
I am not even using the latest driver version 2.45 but 2.41 against Chrome 71 64-bit on Windows 10. Besides, I also use bonigarcia's Webdriver Manager. I have no idea what is wrong with your setup. My Selenium version is 3.14.0, a bit newer than yours, Geb 2.2, Spock 1.1-groovy-2.4, Groovy 2.4.7.
Maybe it is a MacOS thing? I cannot verify that. Maybe you just run my test first, then maybe upgrade your Selenium and if that also does not help try to downgrade the Chrome driver in order to find out if the problem could be driver version related.
Update: I upgraded to Chrome driver 2.45, the test still works.
Update 2022-02-16: Updated the test to work with another example page, because the old URL still exists, but the Javascript there no longer works.

Enable clipboard in automated tests with Protractor and webdriver

I want to test with Protractor an Angular application that accesses the system clipboard using the clipboard api. The problem is that, when executing the test, the Chromium browser asks the user for permission to access the clipboard. I can't close this box from the test, because this is not a DOM element nor an alert window, and it seems not to be any way to access it from Protractor.
clipboard permissions
I have tried to automatically give permission in Chrome, in protractor setup. First, I looked for a command line switch that do it, but it seems not to exist.
Then I found a way that apparently works, but I don't know if its stable: to set an "exception" in Chrome user profile, using the Capabilities of the chrome driver of webdriver. Basically, I add the following lines of my protractor config file:
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'prefs': {
'profile.content_settings.exceptions.clipboard': {
'http://localhost:8000,*': {'last_modified': Date.now(), 'setting': 1}
}
}
}
}
I have found the value by looking inside Default/Preferences file inside my Chrome profile.
It now works for me, but I don't want to use undocumented features, since they can change anytime without notice. Do you know a better way of doing this? Thanks.
If anyone is looking to do something similar with C#, I have adapted the code as such:
var options = new ChromeOptions();
var clipboardException = new Dictionary<string, object> {
{"[*.]myurl.com,*",
new Dictionary<string, object> {
{"last_modified", DateTimeOffset.Now.ToUnixTimeMilliseconds()},
{"setting", 1}
}
}
};
options.AddUserProfilePreference("profile.content_settings.exceptions.clipboard", clipboardException);

pageLoadTimeout is not working in Selenium - Java

I am testing a website in linux host.The page i am accessing loads infinitely so I am trying to set pageLoadTimeout for selenium.
Firefox is triggered correctly but URL is not loading/navigating/added in url bar.just blank firefox window.I am not seeing any errors also.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
driver.get("http://www.example.com");
However if I remove driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS); code is working fine
Selenium version : 3.14.0;
gecko driver : 18 - linux (tested with gecko 16,17 also same issue)
browser : firefox-52
os/platform : linux
If this kind of some issue how do I make sure my driver quit itself after 5 minute.Host will support only firefox 52.
I checked this link but doesnt fix my problem.
Thanks
Jk
You can set the pageload strategy for browser which will then make the page not wait for the full page load for your other Selenium commands to be executed. Below is the sample code snippet in Java. There are three supported values:
normal
This stategy causes Selenium to wait for the full page loading (html content and subresources downloaded and parsed).
eager
This stategy causes Selenium to wait for the DOMContentLoaded event (html content downloaded and parsed only).
none
This strategy causes Selenium to return immediately after the initial page content is fully received (html content downloaded).
By default, when Selenium loads a page, it follows the normal pageLoadStrategy.
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("pageLoadStrategy", "eager");
FirefoxOptions opt = new FirefoxOptions();
opt.merge(caps);
WebDriver driver = new FirefoxDriver(opt);
driver.get("https://www.google.com/");
If you are interested only in the HTML of the page, better use the "eager" strategy.
You haven't mentioned the url you are trying to access but pageLoadTimeout for Selenium works as expected with With Selenium v3.14.0, GeckoDriver v0.23.0 and Firefox Quantum v62.0.3 combination. I am able to see the expected output on the console with the following example which prints TimeoutException occurred. Quiting the program whenever the pageLoadTimeout is triggered:
Code Block:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class A_Firefox_Test
{
public static void main(String[] args)
{
System.setProperty("god.bless.us", "C:/Utility/BrowserDrivers/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
try {
driver.get("https://www.booking.com/hotel/in/the-taj-mahal-palace-tower.html?label=gen173nr-1FCAEoggJCAlhYSDNiBW5vcmVmaGyIAQGYATG4AQbIAQzYAQHoAQH4AQKSAgF5qAID;sid=338ad58d8e83c71e6aa78c67a2996616;dest_id=-2092174;dest_type=city;dist=0;group_adults=2;hip_dst=1;hpos=1;room1=A%2CA;sb_price_type=total;srfid=ccd41231d2f37b82d695970f081412152a59586aX1;srpvid=c71751e539ea01ce;type=total;ucfs=1&#hotelTmpl");
} catch (TimeoutException e) {
System.out.println("TimeoutException occurred. Quiting the program.");
}
driver.quit();
}
}
Console Output:
1539157195615 Marionette INFO Listening on port 1920
Oct 10, 2018 1:09:56 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Oct 10, 2018 1:10:00 PM org.openqa.selenium.remote.ErrorCodes toStatus
INFO: HTTP Status: '500' -> incorrect JSON status mapping for 'timeout' (408 expected)
TimeoutException occurred. Quiting the program.
You can find the detailed stack trace in pageLoadTimeout in Selenium not working
You can find the Pythonic approach to pageLoadTimeout in How to set the timeout of 'driver.get' for python selenium 3.8.0?

How to disable 'This type of file can harm your computer' pop up

I'm using selenium chromedriver for automating web application.
In my application, I need to download xml files. But when I download xml file, I get 'This type of file can harm your computer' pop up. I want to disable this pop up using selenium chromedriver and I want these type of files to be downloaded always. How can this be done?
Selenium version : 2.47.1
Chromedriver version : 2.19
UPDATE it's long standing Chrome bug from 2012.
The problem with XML files started to happen to me as of Chrome 47.0.2526.80 m.
After spending maybe 6 hours trying to turn off every possible security option I tried a different approach.
Ironically, it seems that turning on the Chrome option "Protect you and your device from dangerous sites" removes the message "This type of file can harm your computer. Do you want to keep file.xml anyway?"
I am using 'Ruby' with 'Watir-Webdriver' where the code looks like this:
prefs = {
'safebrowsing' => {
'enabled' => true,
}
}
b = Watir::Browser.new :chrome, :prefs => prefs
Starting the browser like this, with safebrowsing option enabled, downloads the xml files without the message warning. The principle should be the same for Selenium with any programming language.
#####
Edited: 13-04-2017
In latest version of Google Chrome the above solution is not enough. Additionally, it is necessary to start the browser with the following switch:
--safebrowsing-disable-download-protection
Now, the code for starting the browser would look something like this:
b = Watir::Browser.new :chrome, :prefs => prefs, :switches => %w[--safebrowsing-disable-download-protection]))
I am posting below the complete code that got file download working for me:
Hope it helps :-) I am using Java-Selenium
System.setProperty("webdriver.chrome.driver", "C:/chromedriver/chromedriver.exe");
String downloadFilepath = "D:/MyDeskDownload";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
chromePrefs.put("safebrowsing.enabled", "true");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);
Following Python code works for me
chromeOptions = webdriver.ChromeOptions()
prefs = {'safebrowsing.enabled': 'false'}
chromeOptions.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=chromeOptions)
The accepted answer stopped working after a recent update of Chrome. Now you need to use the --safebrowsing-disable-extension-blacklist and --safebrowsing-disable-download-protection command-line switches. This is the WebdriverIO config that works for me:
var driver = require('webdriverio');
var client = driver.remote({
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: {
args: [
'disable-extensions',
'safebrowsing-disable-extension-blacklist',
'safebrowsing-disable-download-protection'
],
prefs: {
'safebrowsing.enabled': true
}
}
}
});
Note that I am also disabling extensions, because they generally interfere with automated testing, but this is not strictly needed to fix the problem with downloading XML and JavaScript files.
I found these switches by reading through this list. You can also see them in the Chromium source.
I came across this recently, using Katalon Studio, Chrome version 88.
Thankfully just the enabling safebrowsing did the trick. You access the settings via "Project Settings" and you navigate to "Desired Capabilities" -> "Web UI" -> "Chrome".
If you don't have a "prefs" setting add it and set the type to Dictionary. Then in the Value add a boolean named "safebrowsing.enabled" and set the value to "true".
Result might look like:
(And you can the default directory setting has nothing to do with this example).
I used all of suggested chrome options in C# and only when my internet connected worked for me but when internet disconnected none of them work for me.
(I'm not sure.may be chrome safebrowsing need to internet connection)
By using older version of chrome(version71) and chromedriver(version 2.46) and after downloading,i saw downloaded XML file name constains 'Unconfirmed' with 'crdownload' extension
and parsing XML file wouldn't work properly.
Finally, creating wait with Thread.Sleep(1000) solved my problem.
IWebDriver Driver;
//chromedriver.exe version2.46 path
string path = #"C:\cd71";
ChromeDriverService driverService = ChromeDriverService.CreateDefaultService(path, "chromedriver.exe");
ChromeOptions options = new ChromeOptions();
// options.AddArgument("headless");
options.AddArgument("--window-position=-32000,-32000");
options.AddUserProfilePreference("download.default_directory", #"c:\xmlFiles");
options.AddUserProfilePreference("download.prompt_for_download", false);
options.AddUserProfilePreference("disable-popup-blocking", "true");
options.AddUserProfilePreference("safebrowsing.enabled", "true");
Driver = new ChromeDriver(driverService, options);
try
{
Driver.Navigate().GoToUrl(url);
Thread.Sleep(1000);
//other works like: XML parse
}
catch
{
}
For context, I had a .csv with a list of .swf flash documents and their respective urls. Since the files could only be accessed after a valid login, I couldn't use a simple requests based solution.
Just like .xml, downloading a .swf triggers a similar prompt.
None of the answers worked for me.
So I stripped away all the extra arguments and settings the above answers proposed and just made the chrome instance headless.
options.add_argument("--headless")
prefs = {
"download.default_directory": "C:\LOL\Flash",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
}
options.add_experimental_option("prefs",prefs)
The only workaround that works for me:
Use argument with path to chrome profile
chromeOptions.add_argument(chrome_profile_path)
Search for file download_file_types.pb in chrome profile folder.
In my case ..chromedriver\my_profile\FileTypePolicies\36\download_file_types.pb
Backup this file and then open with any hexeditor (you can use oline).
Search for the filetype you want to download, i.e. xml and change it to anything i.e. xxx
Im using Google Version 80.0.3987.122 (Official Build) (32-bit) and ChromeDriver 80.0.3987.106. Getting the same error even after adding the below while downloading a .xml file.
$ChromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$ChromeOptions.AddArguments(#(
"--disable-extensions",
"--ignore-certificate-errors"))
$download = "C:\temp\download"
$ChromeOptions.AddUserProfilePreference("safebrowsing.enabled", "true");
$ChromeOptions.AddUserProfilePreference("download.default_directory", $download);
$ChromeOptions.AddUserProfilePreference("download.prompt_for_download", "false");
$ChromeOptions.AddUserProfilePreference("download.directory_upgrade", "true");
$ChromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($chromeOptions)