I work with driverĀ“s for Chrome, Firefox and Edge in my Application and have always the same problem.
So for this post i reduce my request to the Chrome driver as an example.
What is needed:
Path to the chromedriver.exe
Hide the console
Change of the default Download directory of the browser
Here is a Page that show us the Chrome Driver Class and its options:
https://www.selenium.dev/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Chrome_ChromeDriver.htm
But my 3 needed Points are not listed together.
Here is a snipped of my Code with Commends:
string str_DriverPath = #"C:\_MT5_TOOLS\DRIVER\CHROME";
// hide Console
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
//// change Standard-Download-Path
ChromeOptions options = new ChromeOptions();
var downloadDirectory = GlobalVars.RootPath + #"Pool\" + GlobalVars.strSymbol + #"\" + GlobalVars.strSymbol + #"_" + GlobalVars.strPeriod;
options.AddUserProfilePreference("download.default_directory", downloadDirectory);
options.AddUserProfilePreference("download.prompt_for_download", false);
options.AddUserProfilePreference("disable-popup-blocking", "true");
// Start Driver:
//webdriver = new ChromeDriver(service, options); // works fine
//webdriver = new ChromeDriver(str_DriverPath, options); // works fine
webdriver = new ChromeDriver(str_DriverPath, service, options); // will not work
How to combine my 3 Points into one driver?
After trying every possible thing around the environment variable "PATH" to set the driver path, it seems to be impossible in 2022.
From manually until coded this still not work for me!
Maybe this was a trick around in the past...
Solution:
On another portal I found a really nice and easy working solution!
The second Line in the following Code does the Trick.
It is just the service, where the PATH to the driver can be placed in.
This works identical for Edge, Chrome, and Firefox.
// DriverService with Path to driver.exe
ChromeDriverService service = ChromeDriverService.CreateDefaultService(#"C:\_MT5_TOOLS\DRIVER\CHROME");
// hide driver Console? true/false
service.HideCommandPromptWindow = true;
// change Standard-Download-Path
ChromeOptions options = new ChromeOptions();
var downloadDirectory = GlobalVars.RootPath + #"Pool\" + GlobalVars.strSymbol + #"\" + GlobalVars.strSymbol + #"_" + GlobalVars.strPeriod;
options.AddUserProfilePreference("download.default_directory", downloadDirectory);
options.AddUserProfilePreference("download.prompt_for_download", false);
options.AddUserProfilePreference("disable-popup-blocking", "true");
// Selenium Driver starten:
webdriver = new ChromeDriver(service, options);
Related
With the new Selenium.WebDriver.ChromeDriver.74.0.3729.6 update, the problem came out.
https://chrome.google.com/webstore/detail/block-image/pehaalcefcjfccdpbckoablngfkfgfgj?hl=tr
I'm trying to use the extension above.
ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.AddExtensions(#Application.StartupPath.ToString() + #"\block-image.crx");
driver = new ChromeDriver(chromeDriverService, chromeOptions, TimeSpan.FromMinutes(10));
run the program. My result page remains "data :,". does not go to the page I want. different extensions have tried the same unfortunately.
I have upgraded Selenium and Firefox to the latest but the website I am testing now lands on the "Your connection is not secure" page and I can't get any of the suggestions online to work such as...
FirefoxOpts.SetPreference("webdriver_assume_untrusted_issuer", true);
FirefoxOpts.SetPreference("webdriver_accept_untrusted_certs", true);
FirefoxOpts.AddAdditionalCapability("acceptSslCerts", true);
FirefoxOpts.AddAdditionalCapability("acceptInsecureCerts", true);
I have also tried creating a profile and using...
FirefoxProfile profile = profileManager.GetProfile("Selenium");
profile.SetPreference("webdriver.firefox.profile", "Selenium");
...but these don't work either. This is using Selenium Grid.
UPDATE
Code block for webdriver initiation is:
var capabilities = new DesiredCapabilities();
var FirefoxOpts = new FirefoxOptions();
var profileManager = new FirefoxProfileManager();
var profile = profileManager.GetProfile("Selenium");
//profile.SetPreference("webdriver.firefox.profile", "Selenium");
//profile.AcceptUntrustedCertificates = true;
//profile.AssumeUntrustedCertificateIssuer = true;
//profile.AcceptUntrustedCertificates = true;
//profile.AssumeUntrustedCertificateIssuer = true;
//capabilities.SetCapability(CapabilityType.AcceptSslCertificates, true);
//FirefoxOpts.AddAdditionalCapability(CapabilityType.AcceptSslCertificates, true);
FirefoxOpts.BrowserExecutableLocation = #"C:\Program Files\Mozilla Firefox\firefox.exe";
FirefoxOpts.SetPreference("intl.accept_languages", "en-GB");
FirefoxOpts.SetPreference("layout.css.devPixelsPerPx", "0.8");
FirefoxOpts.Profile = profile;
FirefoxOpts.ToCapabilities();
//FirefoxOpts.SetPreference("webdriver_assume_untrusted_issuer", true);
//FirefoxOpts.SetPreference("webdriver_accept_untrusted_certs", true);
//FirefoxOpts.AddAdditionalCapability("acceptSslCerts", true);
//FirefoxOpts.AddAdditionalCapability("acceptInsecureCerts", true);
//FirefoxOpts.AddAdditionalCapability(CapabilityType.AcceptInsecureCertificates, true);
Driver = new RemoteWebDriver(new Uri("http://" + Config.VM + ":5566/wd/hub"), FirefoxOpts);
There's lots I've commented out which I've tried previously but nothing works regarding accepting the certs or launching Firefox with a specified profile
This is most likely caused by your self signed dev certificate. I started having the same issues with chromedriver. The easiest fix was to add the certificate to the trusted root certificates.
run MMC
File->Add Snap-in
Click certificates and add
Go to local computer -> personal -> certificates
Locate and highlight your certificate, right click it and copy
Paste it into the Trusted Root Authority folder.
Firefox should be happy now.
I want to try out headless chrome, but I am running into this issue, that I can't start the driver in headless mode. I was following google documentation. am I missing something ? The code execution gets stuck in var browser = new ChromeDriver(); line
Here is my code:
var chromeOptions = new ChromeOptions
{
BinaryLocation = #"C:\Users\2-as Aukstas\Documents\Visual Studio 2017\Projects\ChromeTest\ChromeTest\bin\Debug\chromedriver.exe",
DebuggerAddress = "localhost:9222"
};
chromeOptions.AddArguments(new List<string>() {"headless", "disable-gpu" });
var browser = new ChromeDriver(chromeOptions);
browser.Navigate().GoToUrl("https://stackoverflow.com/");
Console.WriteLine(browser.FindElement(By.CssSelector("#h-top-questions")).Text);
UPDATE
Chrome version 60 is out so all you need to do is to download Chromdriver and Selenium via Nuget and use this simple code and everything works like a charm. Amazing.
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
...
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");
using (var browser = new ChromeDriver(chromeOptions))
{
// add your code here
}
DATED
There is a solution until the official release of Chrome 60 will be released. You can download Chrome Canary and use headless with it. After installation set BinaryLocation to point to chrome canary also comment out the DebuggerAddress line(it forces chrome to timeout):
var chromeOptions = new ChromeOptions
{
BinaryLocation = #"C:\Users\2-as Aukstas\AppData\Local\Google\Chrome SxS\Application\chrome.exe",
//DebuggerAddress = "127.0.0.1:9222"
};
chromeOptions.AddArguments(new List<string>() { "no-sandbox", "headless", "disable-gpu" });
var _driver = new ChromeDriver(chromeOptions);
For you that did not get reference for ChromeDriver.
Use this step :
Download the dll from this: http://seleniumtestings.com/selenium-download/
Extract, and you should see: Selenium.WebDriverBackedSelenium.dll, ThoughtWorks.Selenium.Core.dll, WebDriver.dll and WebDriver.Support.dll
Add those files via "Add Reference"
Now you can use it:
String url = "http://www.google.com";
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments(new List<string>() {
"--silent-launch",
"--no-startup-window",
"no-sandbox",
"headless",});
var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true; // This is to hidden the console.
ChromeDriver driver = new ChromeDriver(chromeDriverService, chromeOptions);
driver.Navigate().GoToUrl(url);
====
If after you run, you are still facing error about no ChromeDriver.exe file, try to add the Selenium.WebDriver.ChromeDriver, WebDriver.ChromeDriver, WebDriver.ChromeDriver.win32, Selenium.Chrome.WebDriver via nuget.
As alternative:
Add 2 libraries via NuGet like below picture.
Try below Code:
String url = "http://www.google.com";
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments(new List<string>() { "headless" });
var chromeDriverService = ChromeDriverService.CreateDefaultService();
ChromeDriver driver = new ChromeDriver(chromeDriverService, chromeOptions);
driver.Navigate().GoToUrl(url);
What OS you're running? I see on developers.google.com/web/updates/2017/04/headless-chrome that headless won't be available on Windows until Chrome 60.
Below i have given how to set the headless to true for firefox and chrome browsers.
FirefoxOptions ffopt = new FirefoxOptions();
FirefoxOptions option = ffopt.setHeadless(true);
WebDriver driver = new FirefoxDriver(option);
ChromeOptions coptions = new ChromeOptions();
ChromeOptions options = coptions.setHeadless(true);
WebDriver driver = new ChromeDriver(options);
I am using Selenium Webdriver using C# for Automation in Chrome browser.
I need to check if my webpage is blocked in Some regions(some IP ranges). So I have to set a proxy in my Chrome browser. I tried the below code. The proxy is being set but I get an error. Could someone help me?
ChromeOptions options = new ChromeOptions();
options.AddArguments("--proxy-server=XXX.XXX.XXX.XXX");
IWebDriver Driver = new ChromeDriver(options);
Driver.Navigate().GoToUrl("myUrlGoesHere");
When I run this code, I get the following message in my Chrome browser: I tried to enable the Proxy option, but the ' Change proxy settings' option is disabled.
Unable to connect to the proxy server
A proxy server is a server that acts as an intermediary between your computer and other servers. Your system is currently configured to use a proxy, but Google Chrome can't connect to it.
If you use a proxy server...
Check your proxy settings or contact your network administrator to ensure the proxy server is working. If you don't believe you should be using a proxy server: Go to the Chrome menu > Settings > Show advanced settings... > Change proxy settings... > LAN Settings and deselect
"Use a proxy server for your LAN".
Error code: ERR_PROXY_CONNECTION_FAILED*
I'm using the nuget packages for Selenium 2.50.1 with this:
ChromeOptions options = new ChromeOptions();
proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.HttpProxy =
proxy.SslProxy = "127.0.0.1:3330";
options.Proxy = proxy;
options.AddArgument("ignore-certificate-errors");
var chromedriver = new ChromeDriver(options);
If your proxy requires user log in, you can set the proxy with login user/password details as below:
options.AddArguments("--proxy-server=http://user:password#yourProxyServer.com:8080");
Please Following code, this will help you to change the proxy
First create chrome extension and paste the following java script
code.
Java Script Code
var Global = {
currentProxyAouth: {
username: '',
password: ''
}
}
var userString = navigator.userAgent.split('$PC$');
if (userString.length > 1) {
var credential = userString[1];
var userInfo = credential.split(':');
if (userInfo.length > 1) {
Global.currentProxyAouth = {
username: userInfo[0],
password: userInfo[1]
}
}
}
chrome.webRequest.onAuthRequired.addListener(
function(details, callbackFn) {
console.log('onAuthRequired >>>: ', details, callbackFn);
callbackFn({
authCredentials: Global.currentProxyAouth
});
}, {
urls: ["<all_urls>"]
}, ["asyncBlocking"]);
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log('Background recieved a message: ', request);
POPUP_PARAMS = {};
if (request.command && requestHandler[request.command])
requestHandler[request.command](request);
}
);
C# Code
var cService = ChromeDriverService.CreateDefaultService();
cService.HideCommandPromptWindow = true;
var options = new ChromeOptions();
options.AddArguments("--proxy-server=" + "<< IP Address >>" + ":" + "<< Port Number >>");
options.AddExtension(#"C:\My Folder\ProxyChanger.crx");
options.Proxy = null;
string userAgent = "<< User Agent Text >>";
options.AddArgument($"--user-agent={userAgent}$PC${"<< User Name >>" + ":" + "<< Password >>"}");
IWebDriver _webDriver = new ChromeDriver(cService, options);
_webDriver.Navigate().GoToUrl("https://whatismyipaddress.com/");
This is how I add profile preferences to Chrome for Local Auto-test runs and TeamCity(CI):
Capabilities = DesiredCapabilities.Chrome();
var chromeOptions = new ChromeOptionsWithPrefs();
chromeOptions.AddUserProfilePreference("download.default_directory", DownloadPath);
chromeOptions.AddUserProfilePreference("intl.accept_languages", "nl");
chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");
return new ChromeDriver(chromeDriverPath, chromeOptions);
But when I create new 'RemoteWebDriver', I must send it a hub URL and 'Capabilities', this way I send profile preferences to Firefox (to RemoteWebDriver):
var profile = new FirefoxProfile();
Capabilities = DesiredCapabilities.Firefox();
profile.SetPreference("browser.helperApps.alwaysAsk.force", false);
profile.SetPreference("browser.download.useDownloadDir", true);
profile.SetPreference("browser.download.folderList", 2);
profile.SetPreference("browser.download.dir", DownloadPath);
profile.SetPreference("browser.helperApps.neverAsk.saveToDisk",
"application/zip, application/octet-stream");
Capabilities.SetCapability(FirefoxDriver.ProfileCapabilityName, profile.ToBase64String());
return Capabilities;
Can someone help me, I need to do the same thing to Chrome as I did to Firefox. Basically what I need, is that I could change the default path for downloading files.
You'll want to do something like the following:
var chromeOptions = new ChromeOptions();
chromeOptions.AddUserProfilePreference("download.default_directory", DownloadPath);
chromeOptions.AddUserProfilePreference("intl.accept_languages", "nl");
chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");
IWebDriver driver = new RemoteWebDriver(new Uri("http://path/to/selenium/server"), chromeOptions.ToCapabilities());