get the default downloads folder path using Selenium WebDriver - c#

I am new to selenium and I would like to know how do I get the default path of the downloads folder of the browser(I'm using chrome) in the operating system.
I just found a way to set the default path like this:
var chromeOptions = new ChromeOptions();
chromeOptions.AddUserProfilePreference("download.default_directory", path);
chromeOptions.AddUserProfilePreference("intl.accept_languages", "nl");
chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");
var driver = new ChromeDriver("Driver_Path", chromeOptions);

2 ways of achieving this.
One can be found here:
Find Chrome Path
Seconds is to type on browswer (can do that via sendKeys):
chrome://settings
then instruct your webdriver to click on 'advanced'
and finally you can grab the default download directory from the 'location'
If you get stuck anywhere or want further help, please let me know.
Best of luck!

driver.get("chrome://settings/?search=Downloads");
Then take a screenshot.

I had similar need to get the download path, I opted for setting it explicitly. If you could explicitly set the path while creating the driver, you can use it.
For my case, I created a new class inheriting from ChromeDriver which holds the downloads path.
public class MyChromeDriver : ChromeDriver
{
public string DownloadsPath { get; set; }
public MyChromeDriver(ChromeOptions options) : base(options) { }
}
Then when I need a new ChromeDriver, I create new MyChromeDriver and set the downloads path.
var options = new ChromeOptions();
var downloadsPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(downloadsPath);
options.AddUserProfilePreference("download.default_directory", downloadsPath);
options.AddUserProfilePreference("download.prompt_for_download", false);
options.AddUserProfilePreference("disable-popup-blocking", "true");
var myChromeDriver = new MyChromeDriver(options);
myChromeDriver.DownloadsPath = downloadsPath;
Now whenever I need the download path, I have it in myChromeDriver.DownloadPath.

Related

Using Extensions in firefox selenium

I am trying to use an extension in selenium for geckdriver and have found that I need to use FirefoxProfile. From here though, I am lost on what exactly to do. I can't find much help online. Here is what I have, but I get a System.TypeInitializationException error.
FirefoxOptions options = new FirefoxOptions();
FirefoxProfile profile = new FirefoxProfile();
string workingDirectory1 = Environment.CurrentDirectory;
profile.AddExtension(workingDirectory1 + "\\anticaptcha.xpi");
options.Profile = profile;
IWebDriver driver = new FirefoxDriver(options);
driver.Navigate().GoToUrl("https://www.google.com/");
Looks like addExtension method needs some corrections it accepts File as a argument and not a string

Selenium disable Restore pages poup

i am using selenium C#, i am trying to disable the pop up of "crashed" chrome:
i tried to set the profile preferences, but its seems that the it ain't changing at all, the code:
ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("exit_type", "Normal");
options.AddUserProfilePreference("exited_cleanly", "true");
IWebDriver driver = new ChromeDriver(options);
i tried to change the value of exit type to none & None, but without any change at the preferences document.
I'm using C# and I've noticed that chrome driver can be closed propery only when we use Close() method followed by Quit() in finally block. No special options required. I think in java it's the same way. This will help to rid of "Restore pages" while launching chrome with the driver
ChromeOptions options = new ChromeOptions();
options.AddArgument(Configure.chromeProfileDir);
options.AddArgument(Configure.chromePath);
ChromeDriver d = null;
try
{
d = new ChromeDriver(options);
d.Navigate().GoToUrl("https://google.com");
// Your operations...
}
catch(Exception e)
{
// Handle your exceptions...
}
finally
{
try
{
d.Close();
d.Quit();
}
catch(Exception e)
{
}
}
I tested the Answer given by #Icy, and it worked for me. what I used was :
prefs = {'exit_type': 'Normal'}
option.add_experimental_option("prefs", {'profile': prefs})
and it is spoken of by https://superuser.com/a/1343331, only issue is with the method listed there, you will need to edit the file manually every time, so this works way better, tested in may 2021. Just couldn't upvote the answer as I have no reputation yet, and it is the last.
Use below code to handle this pop up:
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-extensions");
options.AddArguments("--disable-application-cache");
driver = new ChromeDriver(options);
i tried this code in java, it solved my problem :))
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir="+profilepath);
options.addArguments("--no-startup-window");
// argument "--no-startup-window" make chrome is failed to start -> selenium will quit chrome normaly
//-> start chrome again, it won't show restore page
try {
driver = new ChromeDriver(options);
}catch(Exception ex){
}
options = new ChromeOptions();
options.addArguments("user-data-dir="+profilepath);
driver = new ChromeDriver(options);
Try this code:
prefs = {'exit_type': 'Normal'}
chrome_options.add_experimental_option("prefs", {'profile': prefs})

Can't open Firefox-based Browser

I tried to open modified FireFox browser using Selenium WebDriver.
(This Firefox-based browser as same as original Firefox, just with additional functionality.)
This Browser opens and then I got Error:
["OpenQA.Selenium.WebDriverException" in WebDriver.dll]
TypeError: Given browserName [object String] "firefox", but my name is [object String] "anotherbrowser"
My code[C#]:
var path = new FirefoxBinary(#"C:\FireFox_BasedBrowser\anotherbrowser.exe");
IWebDriver driver = new FirefoxDriver(path, null); //here's error
After searching I found this advice on Java:
String bname = "Browser name";
FirefoxOptions options = new FirefoxOptions();
options.setBinary("Path to browser binary");
options.setCapability("browserName", bname);
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);
I tried to rewrite it into C#:
DesiredCapabilities cap = DesiredCapabilities.Firefox();
cap.SetCapability("browserName", "anotherbrowser");
cap.SetCapability("firefox_binary", #"C:\FireFox_BasedBrowser\anotherbrowser.exe");
IWebDriver driver = new FirefoxDriver(cap); //here's error
But I also got an error:
["System.ArgumentException" in WebDriver.dll] There is already an option for the browserName capability. Please use
the instead.
Please, help me, I can't find any solutions.
P.s. I can't use original Firefox browser, because it doesn't have same advantages as this modified Firefox.
Use FirefoxDriverService.CreateDefaultService(...) to define another path for Firefox:
var service = FirefoxDriverService.CreateDefaultService(#"C:\drivers", "geckodriver.exe");
service.FirefoxBinaryPath = #"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
var driver = new FirefoxDriver(service);

Selenium.WebDriver with portable FireFox c#

I need to start Selenium with Firefox Portable.
If I start Firefox.exe portable with doublé clic, it starts.
The path to Firefox.exe is correct: A FireFoxPortable folder inside Debug project's folder.
This is the code I use:
var driverService = FirefoxDriverService.CreateDefaultService();
driverService.FirefoxBinaryPath =
Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"FireFoxPortable",
"FireFox.exe");
driverService.HideCommandPromptWindow = true;
driverService.SuppressInitialDiagnosticInformation = true;
var options = new FirefoxOptions();
var driver = new FirefoxDriver(options);
Creating the driver I have an exception -> Cannot find Firefox binary in PATH or default install locations. Make sure Firefox is installed. OS appears to be: Vista
I try this variant, but no work:
var driver = new FirefoxDriver(driverService);
I'm using this nuget packages:
Is this the correct way?
Thanks for your time!
UPDATE ---------------------------------------------
With this code Works:
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"FireFoxPortable", "FireFox.exe");
FirefoxProfile profile = new FirefoxProfile();
var driver = new FirefoxDriver(new FirefoxBinary(path),profile);
But a Warning for new FirefoxDriver Shown: FirefoxDriver should not be constructed with a FirefoxBinary object. Use FirefoxOptions instead. This constructor will be removed in a future release.'
What's the correct way?

How can I force FirefoxDriver to always download a file rather than display dialog [duplicate]

I have written a code to download an excel file, it is working, but it stops as soon as the popup appears. Automatically it should download the file and store in specified location, which is not happening now. Please anyone help in finding a solution for this problem
FirefoxProfile profile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(profile);
profile.setPreference("browser.helperapps.neverAsk.saveToDisk" , "text/csv");
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir","e:\\SampleExcel");
driver.get("http://url");
driver.findElement(By.name("email")).sendKeys("abc#gmail.com");
driver.findElement(By.name("pass")).sendKeys("abc");
driver.findElement(By.id("edit-submit")).click();
driver.findElement(By.id("toolbar-link-admin-config")).click();
driver.findElement(By.linkText("Reports")).click();
driver.findElement(By.xpath("//input[#value='5']")).click();
driver.findElement(By.id("edit-submit")).click();
Try below code
FirefoxProfile profile = new FirefoxProfile();
String path = "D:\\Downloads_sel";
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", path);
profile.setPreference("browser.download.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsksaveToDisk", "application/x-msexcel,application/excel,application/x-excel,application/excel,application/x-excel,application/excel,application/vnd.ms-excel,application/x-excel,application/x-msexcel");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", false);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
profile.setPreference("pdfjs.disabled", true);
WebDriver driver = new FirefoxDriver(profile);
For complete MIME types list follow the link: http://qaautomationworld.blogspot.in/2014/02/file-downlaoding-using-selenium.html
Try to use this code:
FirefoxProfile profile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(profile);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk" , "application/octet-stream;application/csv;text/csv;application/vnd.ms-excel;");
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir","e:\\SampleExcel");
Please replace text by application for preference setting of not prompting download dialog box, like following:
profile.setPreference("browser.helperapps.neverAsk.saveToDisk" , "application/csv");
Just for confirmation, the file which is downloaded is with csv extension, right? If it's not like that, we'll have to make change in above code.

Categories