Selenium screenshot parameter is not valid - c#

Here is my selemium test:
[Test]
public void RunStepsTest()
{
using (var driver = new InternetExplorerDriver())
{
driver.Navigate().GoToUrl(Url);
ExecuteStep(driver, "start");
ExecuteStep(driver, "step1");
ExecuteStep(driver, "step2");
ExecuteStep(driver, "finish");
}
}
private void ExecuteStep(InternetExplorerDriver driver, string stepName)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(x => ExpectedConditions.ElementIsVisible(By.Id(stepName)));
var scrrenshot = driver.GetScreenshot();
scrrenshot.SaveAsFile(Path.Combine(ScreenshotDirectory, stepName + ".jpg"), ScreenshotImageFormat.Jpeg);
var link = driver.FindElement(By.Id(stepName));
link.SendKeys(Keys.Enter);
}
Most of time this test fails on line
scrrenshot.SaveAsFile(Path.Combine(ScreenshotDirectory, stepName + ".jpg"), ScreenshotImageFormat.Jpeg);
with message "Paramter is not valid". What do I do wrong?

In Internet Explorer driver, it's intended to throw this error .
From Github bug tracking :
Because of the limitations of how the IE driver is forced to work in
order to take full-DOM screenshots, screenshots are only supported for
browser windows viewing HTML documents. This is entirely as intended
by the driver (regardless of the behavior of Chrome or Firefox). The
driver is forced by the constraints of the IE browser itself.
Accordingly, I'm closing this as "working as intended".
If you are allowed to use other driver, you can try Firefox or Chrome Driver to have screenshot.

Try this code like this:
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ss.SaveAsFile("e:\\pande", System.Drawing.Imaging.ImageFormat.Jpeg);

Related

Need to get the Process id of IEDriverServer.exe so that I can fetch the child PIDs for browser

The problem is that I need to get the PID of IE browser instances so that I can close the IE browser(Working in C#).
I launched the IE browser using Selenium and then used Driver Service class as :-
InternetExplorerDriverService driverdetails = InternetExplorerDriverService.CreateDefaultService();
Console.WriteLine(driverdetails.Port);
The plan is to get the port and then have its child process. I am able to do so using a debugger by entering the value of Port manually. But, the port fetched by driverdetails.Port was not the actual port used by my driver.
Is there any was, I can find the Port for any given driver service?
For IE i have an alternative to launch IE and get the URL with port which says http://localhost:. However, this is not the case with other browsers. My want is to make the generic code and hence I am using the Driver Service object.
As far as I know, the InternetExplorerDriverService's ProcessID property gets the process ID of the running driver service executable, and we can't get the IE browser instance PID through the InternetExplorer webdriver. If you want to get the PID, you could try to use the Process class.
From your description, it seems that you want to close the IE tab or window by using the IE Webdriver. If that is the case, I suggest you could use InternetExplorerDriver WindowHandles to get the opened windows, then use the switchto method to switch the window and check the url or title, finally, call the Close method to close the IE window. Please refer to the following sample code:
private const string URL = #"https://dillion132.github.io/login.html";
private const string IE_DRIVER_PATH = #"D:\Downloads\webdriver\IEDriverServer_x64_3.14.0"; // where the Selenium IE webdriver EXE is.
static void Main(string[] args)
{
InternetExplorerOptions opts2 = new InternetExplorerOptions() { InitialBrowserUrl = "https://www.bing.com", IntroduceInstabilityByIgnoringProtectedModeSettings = true, IgnoreZoomLevel = true };
using (var driver = new InternetExplorerDriver(IE_DRIVER_PATH, opts2))
{
driver.Navigate();
Thread.Sleep(5000);
//execute javascript script
var element = driver.FindElementById("sb_form_q");
var script = "document.getElementById('sb_form_q').value = 'webdriver'; console.log('webdriver')";
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript(script, element);
InternetExplorerDriverService driverdetails = InternetExplorerDriverService.CreateDefaultService(IE_DRIVER_PATH);
Console.WriteLine(driverdetails.Port);
// open multiple IE windows using webdriver.
string url = "https://www.google.com/";
string javaScript = "window.open('" + url + "','_blank');";
IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)driver;
jsExecutor.ExecuteScript(javaScript);
Thread.Sleep(5000);
//get all opened windows (by using IE Webdriver )
var windowlist = driver.WindowHandles;
Console.WriteLine(windowlist.Count);
//loop through the list and switchto the window, and then check the url
if(windowlist.Count > 1)
{
foreach (var item in windowlist)
{
driver.SwitchTo().Window(item);
Console.WriteLine(driver.Url);
if(driver.Url.Contains("https://www.bing.com"))
{
driver.Close(); //use the Close method to close the window. The Quit method will close the browser window and dispose the webdriver.
}
}
}
Console.ReadKey();
}
Console.ReadKey();
}

Getting System.ArgumentException when running C# Selenium Test

I'm learning how to write selenium tests in C# and am getting this error when trying to run the test case below. It is failing on: IWebElement query = driver.FindElement(By.Name("q"));
Test method SeleniumDemo.SearchGoogle.SearchForCheese threw exception:
System.ArgumentException: elementDictionary (Parameter 'The specified dictionary does not contain an element reference')
Code:
[TestMethod]
public void SearchForCheese()
{
using (var driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)))
{
driver.Navigate().GoToUrl("http://www.google.com");
// Find text input
IWebElement query = driver.FindElement(By.Name("q"));
// Enter something to search for
query.SendKeys("cheese");
// Submit form
query.Submit();
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(d => d.Title.Contains("cheese"));
Assert.AreEqual(driver.Title, "cheese - Google Search");
};
}
Any ideas? Thank you in advance!
Check and make sure your ChromeDriver() version matches what is on your local machine.
Below is an XUnit test that will re-create your issue using the WebDriverManager NuGet package where you can manually specify which version of webdriver you want downloaded if it's not available on your machine:
[Fact]
public void ChromeDriverThrows_ArgumentException_True()
{
var google = "https://www.google.com/";
var message = "elementDictionary (Parameter 'The specified
dictionary does not contain an element
reference')";
// Specify a different of ChromeDriver than what is installed on machine.
_ = new DriverManager().SetUpDriver(
"https://chromedriver.storage.googleapis.com/2.25/chromedriver_win32.zip",
Path.Combine(Directory.GetCurrentDirectory(), "chromedriver.exe"),
"chromedriver.exe"
);
var driver = new ChromeDriver();
driver.Navigate().GoToUrl(google);
var exception = Assert.Throws<ArgumentException>(() => driver.FindElement(By.Name("q")));
Assert.True(message == exception.Message, $"{exception.Message}");
}
If you choose to use WebDriverManager in your project, you can use automatically set the below to automatically download a chromedriver.exe matching the version of Chrome installed in your machine so you don't have to manually manage them:
new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser);

How to launch a specific URL with Firefox in C#

I'm trying to launch a specific URL using Firefox. But I'm only able to open Firefox browser and not able to launch that URL.
class BrowserHelper
{
IWebDriver driver;
string path = Path.Combine(Environment.CurrentDirectory, #"gecko\\");
public void Navigate(string url)
{
path = path.Replace(#"\", #"\\");
var driverService = FirefoxDriverService.CreateDefaultService(path);
driverService.HideCommandPromptWindow = true;
if (driver == null)
{
driver = new FirefoxDriver(driverService);
}
driver.Url = url;
driver.Navigate().GoToUrl(driver.Url);
driver.Manage().Window.Maximize();
}
}
class Realtest
{
BrowserHelper BH = new BrowserHelper();
public void test()
{
string search ="apple";
BH.Navigate("https://www.google.com/search?q=" + search);
}
}
And I can only get this page:
Here's the final URL I want to launch: https://www.google.com.sg/search?q=apple
Any suggestions? Thanks in advance.
I have tried the below code (in Java), and it's working fine by launching the browser and loading the URL also.
System.setProperty("webdriver.gecko.driver","Drivers/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com.sg/search?q=apple");
So I feel the problem is with geckodriver version and FireFox browser installed in your local machine. I would suggest you update FireFox and geckodriver to the latest version.
There is also a pretty easy solution using the command line with c#.
Simply execute the following command to open a new Firefox Tab with the given URL:
start firefox wikipedia.de
You can also start a new Firefox instance if you wish:
start firefox -new-instance wikipedia.de
Last but not least the .Net Code to execute the commands in CLI:
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
Arguments = "/c start firefox wikipedia.de",
CreateNoWindow = true,
FileName = "CMD.exe"
});
There is also a lot of other stuff that can be done with Firefox commandLine paramters. You an find all of them here:
https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options?redirectlocale=en-US&redirectslug=Command_Line_Options
This also works with chrome and opera, simply call
start opera wikipedia.de
instead of firefox.
You do not need to set driver.Url, remove that line.
driver.Navigate().GoToUrl(url);
driver.Manage().Window.Maximize();
Also, if you simply want to launch a single URL without interacting with the page, then Selenium is overkill.

Error using Selenium Webdriver headless

I'm using a chrome Webdriver to take a screenshot on a page, if I use the "headless" argument I get this error:
[1127/115120.051:INFO:CONSOLE(157)] "Deprecation warning: moment
construction falls back to js Date.
This is discouraged and will be removed in upcoming major release.
Please refer to https://github.com/moment/moment/issues/1407 for more info.
at Function.createFromInputFallback (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:157:187)
at ie (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:157:664)
at De (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:158:1390)
at Me (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:158:1287)
at Se (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:158:1007)
at Ne (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:158:1703)
at Oe (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:158:1737)
at t (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:154:2701)
at e (https://s-new.tradingview.com/static/bundles/blackfriday-dialog.dba1b059b906a510ba6c.js:1:580)
at i.<anonymous> (https://s-new.tradingview.com/static/bundles/blackfriday-dialog.dba1b059b906a510ba6c.js:1:2029)", source: https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js (157)
I'm not sure if the error and the info message are related.
The same thing happens using phantomJS, but works fine if the chrome window is shown, although that's not an option since every time the screenshot gets taken, chrome steals focus.
here's what I'm trying:
static void Main()
{
ChromeOptions options = new ChromeOptions();
options.AddArgument("--disable-notifications");
options.AddArguments("--disable-gpu");
options.AddArgument("--headless");
var driver = new ChromeDriver(options);
driver.Url = "https://uk.tradingview.com/chart/?symbol=FX:GBPUSD";
var webElement = driver.FindElementByClassName("chart-widget");
string fileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".jpg";
Byte[] byteArray = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap(new System.IO.MemoryStream(byteArray));
}
the error happens as the address is being passed to the driver.Url.
Any idea how to fix it or work around it?

NoSuchElementException using PhantomJS 1.9.2 in Visual Studio/C#

I've read all prior posts and tried all suggestions. I've verified the page is loading via taking a screenshot. It's there. I have a 30 second implicit wait in place, which PhantomJS waits for. I have a fully qualified URL. And i've tested the same simple code snippet below with ChromeDriver and it works by flipping to that driver. Any ideas?
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var d = new PhantomJSDriver();
//var d = new ChromeDriver();
try
{
var s = "abc";
d.Manage().Window.Maximize();
d.Manage().Timeouts().ImplicitlyWait(System.TimeSpan.FromSeconds(10));
d.Navigate().GoToUrl("http://www.google.com");
var e = d.FindElement(By.Name("q"));
e.SendKeys(s);
e.Submit();
Assert.AreEqual<String>(s + " - Google Search", d.Title);
}
catch(Exception e)
{
((ITakesScreenshot)d).GetScreenshot().SaveAsFile("c:\\exception.png", System.Drawing.Imaging.ImageFormat.Png);
Console.WriteLine(d.PageSource);
throw e;
}
finally
{
d.Quit();
}
}
Google may response with different HTML code depending on user agent and/or viewport size. Set a viewport of a desktop browser (like 1280x1024) to get a desktop version, whereas default PhantomJS viewport of 400x300 gets a lighter mobile version.
On how to change viewport size, see https://stackoverflow.com/a/23840494/2715393

Categories

Resources