IDevTools instance does not contain CreateDevToolsSession method - c#

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");
}

Related

Selenium 4 C# Chrome DevTools

I would like to intercept the error messages from network Fetch/XHR. Which method should I take or how can I make a connection and intercept this information?
I know this is necessary code base:
driver = new ChromeDriver();
driver.Manage().Window.Maximize();
devTools = driver as IDevTools;
session = devTools.GetDevToolsSession();
devToolsSession = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
devToolsSession.Network.Enable(new Network.EnableCommandSettings());
I tried to create an EventHandler but unfortunately, this requestID of event doesn't match with requestID of the DevTools parameter. How should I get requestID and what method do I need to intercept errors which appear on the preview page of the Network
Try this
IDevTools devTools = driver.OriginDriver as IDevTools;
DevToolsSession session = devTools.GetDevToolsSession();
FetchAdapter fetchAdapter = session.GetVersionSpecificDomains<OpenQA.Selenium.DevTools.V95.DevToolsSessionDomains>().Fetch;
var enableCommandSettings = new OpenQA.Selenium.DevTools.V95.Fetch.EnableCommandSettings();
var requestPattern = new OpenQA.Selenium.DevTools.V95.Fetch.RequestPattern();
requestPattern.RequestStage = RequestStage.Request;
requestPattern.ResourceType = ResourceType.XHR;
enableCommandSettings.Patterns = new OpenQA.Selenium.DevTools.V95.Fetch.RequestPattern[] { requestPattern };
fetchAdapter.Enable(enableCommandSettings);
EventHandler<OpenQA.Selenium.DevTools.V95.Fetch.RequestPausedEventArgs> requestIntercepted = (sender, e) =>
{
Requests.Add(e.Request);
fetchAdapter.ContinueRequest(new OpenQA.Selenium.DevTools.V95.Fetch.ContinueRequestCommandSettings()
{
RequestId = e.RequestId
});
};
fetchAdapter.RequestPaused += requestIntercepted;

Selenium much slower in Firefox than Chrome

I have a very simple selenium test the completes a login form. Using the ChromeDriver it completes in around 5 seconds, but using FirefoxDriver it takes around 30 seconds, with a multiple second pause between each step of the code.
My C# code is:
var browser = "firefox";
if (browser == "firefox")
{
var options = new FirefoxOptions();
options.AcceptInsecureCertificates = true;
options.PageLoadStrategy = PageLoadStrategy.Eager;
_driver = new FirefoxDriver(options);
}
else // Chrome
{
var options = new ChromeOptions();
options.AcceptInsecureCertificates = true;
_driver = new ChromeDriver(options);
}
_driver.Url = "...";
_driver.FindElement(By.Id("UserName")).SendKeys(username);
_driver.FindElement(By.Id("Password")).SendKeys(password);
_driver.FindElement(By.CssSelector("input[type=\"submit\"][value=\"" + JavaScriptEncoder.Default.Encode(buttonLabel) + "\"]")).Click();
_driver.Title.Should().Be(pageTitle);
_driver.Dispose();
I have tried both 32 bit and 64 bit versions of Firefox, but it made no difference.
How can I debug where the pause is coming from?

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