Run Selenium grid 2 with custom firefox profile - c#

How to run Selenium grid 2 with custom firefox profile from code.
Here is code I'm having now:
DesiredCapabilities capabilities = DesiredCapabilities.Firefox();
capabilities.SetCapability(CapabilityType.AcceptSslCertificates, true);
capabilities.SetCapability(CapabilityType.HasNativeEvents, false);
capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
capabilities.IsJavaScriptEnabled = true;
Uri url = new Uri("http://localhost:4444/wd/hub");
RemoteWebDriver driver = new RemoteWebDriver(url, capabilities);
return driver;
The only thing I left is to force Selenium grid use my custom profile.

Found solution:
var firefoxProfile = new FirefoxProfile();
// configure firefoxProfile ...
DesiredCapabilities capabilities = DesiredCapabilities.Firefox();
capabilities.SetCapability(CapabilityType.AcceptSslCertificates, true);
capabilities.SetCapability(CapabilityType.HasNativeEvents, false);
capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
capabilities.IsJavaScriptEnabled = true;
capabilities.SetCapability(FirefoxDriver.ProfileCapabilityName, firefoxProfile.ToBase64String());
Uri url = new Uri("http://localhost:4444/wd/hub");
RemoteWebDriver driver = new RemoteWebDriver(url, capabilities);
return driver;

Related

IDevTools instance does not contain CreateDevToolsSession method

I'm trying to intercept URLs containing a substring in C# using selenium chrome webdriver 4.0.0-beta4.
This is what I found and changed a little bit:
using V89 = OpenQA.Selenium.DevTools.V89;
using V89Net = OpenQA.Selenium.DevTools.V89.Network;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.DevTools;
ChromeOptions options = new ChromeOptions();
ChromeDriver webDriver;
IDevTools devTools;
public void InterceptRequestWithFetch(string url)
{
options.BinaryLocation = #"C:\Program Files\Google\Chrome Beta\Application\chrome.exe";
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = AppDomain.CurrentDomain.BaseDirectory + "chromedriver.log";
service.EnableVerboseLogging = true;
webDriver = new ChromeDriver(service, options);
devTools = webDriver as IDevTools;
var devToolsSession = devTools.CreateDevToolsSession();
var fetch = devToolsSession.GetVersionSpecificDomains<V89.DevToolsSessionDomains>().Fetch;
var enableCommandSettings = new V89.Fetch.EnableCommandSettings();
var requestPattern = new V89.Fetch.RequestPattern();
requestPattern.RequestStage = V89.Fetch.RequestStage.Response;
requestPattern.ResourceType = V89Net.ResourceType.XHR;
requestPattern.UrlPattern = "*://*/*.jpg*";
enableCommandSettings.Patterns = new V89.Fetch.RequestPattern[] { requestPattern };
fetch.Enable(enableCommandSettings);
fetch.RequestPaused += RequestIntercepted;
webDriver.Navigate().GoToUrl(url);
}
void RequestIntercepted(object sender, V89.Fetch.RequestPausedEventArgs e)
{
richTextBox1.AppendText(e.Request.Url);
webDriver.Quit();
}
The problem is CreateDevToolsSession() does not exists and it seems like GetDevToolsSession() is the only option which does totally different job, but I tried it anyway and then my form froze, and codes past that line never executed.
I searched last three days for a solution but its just CreateDevToolsSession(). How can I use the DevTools if I won't be able to create a session?
This worked for me. Might not be exactly what you want, but it sets up devtools and can do whatever you normally would.
using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.DevTools.V96.Network;
using DevToolsSessionDomains = OpenQA.Selenium.DevTools.V96.DevToolsSessionDomains;
public void DevtoolsExample()
{
IDevToolsSession session;
DevToolsSessionDomains devToolsSession;
//Setup WebDriver and devtools
driver = new ChromeDriver();
var baseUrl = ConfigurationHelper.Get<string>("TargetUrl");
//*this appears to create devtools session or get existing
IDevTools devTools = driver as IDevTools;
session = devTools.GetDevToolsSession();
devToolsSession = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
devToolsSession.Network.Enable(new EnableCommandSettings());
devToolsSession.Network.SetBlockedURLs(new SetBlockedURLsCommandSettings()
{
Urls = new string[] { "*://*/*.css", "*://*/*.jpg", "*://*/*.png" }
//Urls = new string[] { }
});
driver.Navigate().GoToUrl("https://someUrl.com");
}

about tor selenium C#

Hello guys I try to use tor in C# I find some sources on the website but I have some problems
please help me :
WebDriverWait Wait;
IWebDriver Driver;
String torBinaryPath = #"D:\Tor Browser\Browser\firefox.exe";
Process TorProcess = new Process();
TorProcess.StartInfo.FileName = torBinaryPath;
TorProcess.StartInfo.Arguments = "-n";
TorProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
TorProcess.Start();
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("network.proxy.type", 1);
profile.SetPreference("network.proxy.socks", "127.0.0.1");
profile.SetPreference("network.proxy.socks_port", 9150);
FirefoxOptions options = new FirefoxOptions();
options.Profile = profile;
Driver = new FirefoxDriver(options);
Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(60));
Driver.Navigate().GoToUrl(#"http://whatismyipaddress.com/");
the problem is enter image description here
You need to use an option and not a profile.
Please check the example below.
FirefoxOptions opt = new FirefoxOptions();
opt.Profile = new FirefoxProfile();
opt.Profile.SetPreference("network.proxy.type", 1);
opt.Profile.SetPreference("network.proxy.socks", "127.0.0.1");
opt.Profile.SetPreference("network.proxy.socks_port", 9150);
this.Driver = new FirefoxDriver(opt);

How to get Saucelabs tunnelidentifier set up using AddAdditionalCapability in C#?

Here is my sample code which I tried but I cannot get the tunnelidentifier set up and launch test url. Other than generic sites which are not blocked by proxy. Any help is appreciated. Thanks
[Test]
public void SimpleTest1()
{
Uri sauceHubURL = new Uri("https://USERNAME:SOMEACCESSKEY#123.saucelabs.com:443/wd/hub");
InternetExplorerOptions options = new InternetExplorerOptions();
options.AddAdditionalCapability("parentTunnel", "PQSauceLabs");
options.AddAdditionalCapability("tunnelIdentifier", "Mys-sauce-Tests");
options.AddAdditionalCapability("EnsureCleanSession", true);
string url = "https://www.google.com";
string companyurl = "https://www.sample.com";
var remoteDriver = new RemoteWebDriver(sauceHubURL, options.ToCapabilities(), TimeSpan.FromSeconds(300));
remoteDriver.Navigate().GoToUrl(url);
//remoteDriver.SwitchTo().Alert().SetAuthenticationCredentials("q25215", "test#");
//IAlert alert = remoteDriver.SwitchTo().Alert();
//alert.SendKeys("q25215"+ Keys.Tab + "test#" + Keys.Tab);
//alert.Accept();
string title = remoteDriver.Title;
Console.WriteLine("Getting the page title: " + title);
NUnit.Framework.Assert.AreEqual(title, "Google", "Compared values not equal");
remoteDriver.Quit();
}
I'm guessing this was run using the W3C Selenium bindings, so the sauce-specific options like parentTunnel need to be namespaced under sauce:options:
var driverOptions = new FirefoxOptions();
driverOptions.PlatformName = "macOS 10.13";
var sauceOptions = new Dictionary<string, object>();
sauceOptions.Add("username", sauceUserName);
sauceOptions.Add("accessKey", sauceAccessKey);
sauceOptions.Add("name", TestContext.CurrentContext.Test.Name);
sauceOptions.Add("parentTunnel", "Mys-sauce-Tests");
sauceOptions.Add("tunnelIdentifier", "PQSauceLabs");
driverOptions.AddAdditionalOption("sauce:options", sauceOptions);
//create a new Remote driver that will allow your test to send
//commands to the Sauce Labs grid so that Sauce can execute your tests
_driver = new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"),
driverOptions);

Selenium WebDriver Factory picking same driver

I am making an WinForms application, using Visual Studio with Selenium webdriver. I am running some tests using different browser for each test, that are launch at the click of different winforms buttons.
I have created an Webdriver Factory class as follows:
class BrowserFactory
{
private static readonly IDictionary<string, IWebDriver> Drivers = new Dictionary<string, IWebDriver>();
private static IWebDriver driver;
public static IWebDriver Driver
{
get
{
if (driver == null)
throw new NullReferenceException("The WebDriver browser instance was not initialized. You should first call the method InitBrowser.");
return driver;
}
private set
{
driver = value;
}
}
public static void InitBrowser(string browserName)
{
switch (browserName)
{
case "Firefox":
if (driver == null)
{
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
options.Profile = profile;
options.BrowserExecutableLocation = $#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\Internet JS4\App\firefox64\firefox.exe";
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService($#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}");
driver = new FirefoxDriver(service, options);
Drivers.Add("Firefox", driver);
}
break;
case "Chrome":
if (driver == null)
{
var service = ChromeDriverService.CreateDefaultService($#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\ChromeDriver");
var options = new ChromeOptions();
service.HideCommandPromptWindow = true;
options.BinaryLocation = $#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\GoogleChromePortable\App\Chrome-bin\chrome.exe";
options.AddUserProfilePreference("disable-popup-blocking", "true");
driver = new ChromeDriver(service, options);
Drivers.Add("ChromeAscuns", driver);
}
break;
}
}
The code for first button:
BrowserFactory.InitBrowser("Firefox");
BrowserFactory.Driver.Navigate().GoToUrl("http://www.google.com");
The code for the second button:
BrowserFactory.InitBrowser("Chrome");
BrowserFactory.driver.Navigate().GoToUrl("http://www.bing.com");
When I click any of the buttons, it launches the correct webdriver (Firefox for first button and Chrome for the second). However, when I click the other button, it uses the same webdriver browser as the first occurence.
What am I missing in the code?
You appear to want to cache web drivers and reuse them. The problem is you are checking to see if a "driver" is already created, and if not create one, and cache that instance in a dictionary.
You need to consult the dictionary first before entering the switch statement and exit the method prematurely if a web driver by that name already exists. You also need to assume that when you fall in to the switch statement you will always be creating a new web driver.
public static void InitBrowser(string browserName)
{
if (Drivers.ContainsKey(browserName))
{
// Switch to existing web driver
driver = Drivers[browserName];
return;
}
// Initialize new web driver
switch (browserName)
{
case "Firefox":
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
options.Profile = profile;
options.BrowserExecutableLocation = $#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\Internet JS4\App\firefox64\firefox.exe";
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService($#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}");
driver = new FirefoxDriver(service, options);
Drivers.Add("Firefox", driver);
break;
case "Chrome":
var service = ChromeDriverService.CreateDefaultService($#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\ChromeDriver");
var options = new ChromeOptions();
service.HideCommandPromptWindow = true;
options.BinaryLocation = $#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\GoogleChromePortable\App\Chrome-bin\chrome.exe";
options.AddUserProfilePreference("disable-popup-blocking", "true");
driver = new ChromeDriver(service, options);
Drivers.Add("ChromeAscuns", driver);
break;
}
}

PhantomJS C# how to change Default language

Trying to set a Default language in my program. But after much googling i dident find any answers.
How can i input standard english accept language?
is there any document i can read for all functions i can use in c# with PhantomJS? I dident find anything more then playing in Visualstudio controlls.
var driverService = PhantomJSDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
driverService.LoadImages = false;
driverService.SslProtocol = "tlsv1";
driverService.IgnoreSslErrors = true;
driverService.ProxyType = "http";
driverService.Proxy = "";
using (var driver = new PhantomJSDriver(driverService))
{
driver.Manage().Window.Size = new Size(1920, 1080); // Size is a type in assembly "System.Drawing"
driver.Manage().Cookies.DeleteAllCookies();
driver.Url = "https://www.thewebsite.com";
Thread.Sleep(5000); // 5sec
try
{
driver.FindElement(By.Name("email")).SendKeys("MyEmail");
driver.FindElement(By.Name("fullName")).SendKeys("MyName");
driver.FindElement(By.Name("username")).SendKeys("MyUsername");
driver.FindElement(By.Name("password")).SendKeys("MyPassword");
driver.TakeScreenshot().SaveAsFile("LetsSnapascreenshot.png", ImageFormat.Png);
}
catch (OpenQA.Selenium.NoSuchElementException exception)
{
var exmsg = exception;
driver.TakeScreenshot().SaveAsFile("Snaperrorscreenshot.png", ImageFormat.Png);
}
}
I found the solution for this if anyone else is looking for it.
PhantomJSOptions options = new PhantomJSOptions();
options.AddAdditionalCapability("phantomjs.page.customHeaders.Accept-Language", "en,en;q=0.5");
IWebDriver driver = new PhantomJSDriver(options);
And now it outputs the accept-Language correct
you can try to add a header
PhantomJSOptions options = new PhantomJSOptions();
options.AddAdditionalCapability("Accept-Language","en-DE,en;q=0.5");
IWebDriver driver = new PhantomJSDriver(options);
or write in your index.html as described in this answer
<script>
localStorage.lang = 'en';
</script>

Categories