Error using Selenium Webdriver headless - c#

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?

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

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.

Selenium screenshot parameter is not valid

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

chrome webdriver cannot open new tab

I'm trying to open up a new tab in Selenium.WebDriver.ChromeDriver" version="2.21.0.0" but it doesn't open anything, however if I move the debug tracking step back to the line "body.SendKeys(Keys.Control + 't')" to rerun the second time, it works ??
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
IWebElement body = wait.Until(ExpectedConditions.ElementIsVisible(By.TagName("body")));
Thread.Sleep(2000);
body.SendKeys(Keys.Control + 't');
Update: It seems to put a stop on chrome, it does open the tab properly. So instead of using Thread.sleep, just try:
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
js.ExecuteScript("return window.stop");
body.SendKeys(Keys.Control + 't');
To open a new tab with Chrome:
var driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://stackoverflow.com");
// open a new tab and set the context
driver.ExecuteScript("window.open('_blank', 'tab2');");
driver.SwitchTo().Window("tab2");
driver.Navigate().GoToUrl("https://www.google.com");
Use the following code for your problem :
Actions act = new Actions(driver);
act.sendKeys(Keys.CONTROL,"t").build().perform();

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

Is there any way to maximize the browser window using WebDriver (Selenium 2) with C#?
driver.Manage().Window.Maximize();
This works for IE and Firefox. Chrome does not work. There is a bug submitted for this on ChromeDriver project.
Meanwhile, the get around for the chrome is to implement what Joey V. and Coder323 suggested.
ChromeOptions options = new ChromeOptions();
options.addArgument("--start-maximized");
driver = new ChromeDriver(options);
Java
driver.manage().window().maximize();
Python
driver.maximize_window()
Ruby
#driver.manage.window.maximize
OR
max_width, max_height = driver.execute_script("return [window.screen.availWidth, window.screen.availHeight];")
#driver.manage.window.resize_to(max_width, max_height)
OR
target_size = Selenium::WebDriver::Dimension.new(1600, 1268)
#driver.manage.window.size = target_size
For IE and Firefox:
driver.manage().window().maximize();
For Chrome:
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver( options )
There's an outstanding issue to add this functionality to WebDriver, which can be tracked here: http://code.google.com/p/selenium/issues/detail?id=174
A workaround would be to use the JavascriptExector as follows:
public void resizeTest() {
driver.Navigate().GoToUrl("http://www.example.com/");
((IJavaScriptExecutor)driver).ExecuteScript("window.resizeTo(1024, 768);");
}
Test step/scenario:
1. Open a browser and navigate to TestURL
2. Maximize the browser
Maximize the browser with C# (.NET):
driver.Manage().Window.Maximize();
Maximize the browser with Java :
driver.manage().window().maximize();
Another way to do with Java:
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenResolution = new Dimension((int)
toolkit.getScreenSize().getWidth(), (int)
toolkit.getScreenSize().getHeight());
driver.manage().window().setSize(screenResolution);
You can use something like this (C#):
driver.Manage().Window.Size = new Size(1024, 768);
If you are using the Chrome Driver you can set the capabilities
var capabilities = new DesiredCapabilities();
var switches = new List<string>
{
"--start-maximized"
};
capabilities.SetCapability("chrome.switches", switches);
new ChromeDriver(chromedriver_path, capabilities);
Simply use Window.Maximize() command
WebDriver driver= new ChromeDriver()
driver.Manage().Window.Maximize();
For Java:
driver.manage().window().maximize();
It will work in IE, Mozilla, Chrome
The following Selenium Java code snippet worked for me:
driver.manage().window().setPosition(new Point(0,0));
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Dimension dim = new Dimension((int) screenSize.getWidth(), (int) screenSize.getHeight());
driver.manage().window().setSize(dim);
I had the same problem, but the problem can be solved by using following code.
driver.manage().window().fullscreen();
For C#:
driver.Manage().Window.Maximize();
For Java:
driver.manage().window().maximize();
We have observed bug with new driver libraries. You can use slightly old jars which are able to handle new browsers versions.
The main generic option is :-
driver.manage().window().maximize();
You can also use other option for maximizing the browser window.
Example:-
Add below option and pass it to driver:-
chromeOptions.addArguments("--start-maximized");
The full code will look like below :-
System.setProperty("webdriver.chrome.driver","D:\\Workspace\\JmeterWebdriverProject\\src\\lib\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
driver = new ChromeDriver(chromeOptions);
OR
Toolkit toolkit = Toolkit.getDefaultToolkit();
int Width = (int) toolkit.getScreenSize().getWidth();
int Height = (int)toolkit.getScreenSize().getHeight();
//For Dimension class, Import following library "org.openqa.selenium.Dimension"
driver.manage().window().setSize(new Dimension(Width,Height));
driver.get("https://google.com");
Try this on safari :-
JavascriptExecutor jse = (JavascriptExecutor)driver;
String screenWidth = jse.executeScript("return screen.availWidth").toString();
String screenHeight = jse.executeScript("return screen.availHeight").toString();
int intScreenWidth = Integer.parseInt(screenWidth);
int intScreenHeight = Integer.parseInt(screenHeight);
Dimension d = new Dimension(intScreenWidth, intScreenHeight);
driver.manage.window.setSize(d);
using System.Windows.Forms;
using System.Drawing;
public static void MaximizeBrowser(this IE myBrowser)
{
myBrowser.SizeWindow(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
}
I used Jim's code, but slightly modified for use with WatiN and C# to maximize the browser.
You can use Selenium Emulation in WebDriver:
selenium = new WebDriverBackedSelenium(driver,url);
selenium.windowMaximize();
I used this solution
OpenQA.Selenium.Chrome.ChromeOptions chromeoptions = new OpenQA.Selenium.Chrome.ChromeOptions();
chromeoptions.AddArgument("--start-maximized");
OpenQA.Selenium.Chrome.ChromeDriver chrome = new OpenQA.Selenium.Chrome.ChromeDriver(chromeoptions);
For Chrome
ChromeOptions options = new ChromeOptions();
IWebDriver driver = new ChromeDriver(options);
driver.Manage().Window.Maximize();
There is a function that you can use to maximize the window in Python which is window_maximize(). And this is how I'm using it.Hope this helps -
from selenium import selenium
sel = selenium('localhost', 4444, '*firefox', 'http://10.77.21.67/')
sel.start()
sel.open('/')
sel.wait_for_page_to_load(60000)
#sel.window_focus()
sel.window_maximize()
png = sel.capture_screenshot_to_string()
f = open('screenshot.png', 'wb')
f.write(png.decode('base64'))
f.close()
sel.stop()
C# client drivers:
driver = new FirefoxDriver(firefoxProfile);
driver.Manage().Window.Size = new System.Drawing.Size(System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width+10, System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height+10);
===> also add a reference to the .NET assembly "System.Windows.Forms"
... the only problem is that it's not positioned correctly
... please comment if you can correct this
Here's what worked for me in C#, firefoxDriver is global to the class:
in the usings:
using System.Drawing;
using System.Windows.Forms;
in the code:
this.firefoxDriver = new FirefoxDriver();
this.firefoxDriver.Manage().Window.Position = new Point(0, 0);
this.firefoxDriver.Manage().Window.Size = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
For Webdriverjs (node.js), the following maximizes chrome window.
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).build();
driver.manage().window().maximize();
driver.get('hxxp://localhost:8888');
This option is fine for me :
ChromeOptions options = new ChromeOptions();
options.addArguments("start-fullscreen");
This option works on all OS.
The below line of code would maximize IE, Chrome and Mozilla
driver.manage().window().maximize();
The above line of code and other workarounds mentioned in the post did not work for NodeWebKit browser, so as a workaround i had to use native C# code as mentioned below:
public static void MaximiseNWKBrowser(IWebDriver d)
{
var body = UICommon.GetElement(By.TagName("body"), d);
body.Click();
string alt = "%";
string space = " ";
string down = "{DOWN}";
string enter = "{ENTER}";
SendKeys.SendWait(alt + space);
for(var i = 1; i <= 6; i++)
{
SendKeys.SendWait(down);
}
SendKeys.SendWait(enter);
}
So this workaround basically uses "ALT+SPACE" to bring up the browser action menu to select "MAXIMIZE" from the options and presses "ENTER"
Through the below code i'm able to maximize the window,
((JavascriptExecutor) driver).executeScript("if(window.screen){
window.moveTo(0, 0);
window.resizeTo(window.screen.availWidth, window.screen.availHeight);
};");
This is working fine for me.
Capybara.current_session.driver.browser.manage.window.resize_to(1800, 1000)
I tried many of the answers above, but none work well.
My chrome driver version is 2.7 and Iam using selenium-java vesion is 2.9.0.
The official document suggests using:
var capabilities = new DesiredCapabilities();
var switches = new List<string>
{
"--start-maximized"
};
capabilities.SetCapability("chrome.switches", switches);
new ChromeDriver(chromedriver_path, capabilities);
The above also does not work. I checked the chrome driver JsonWireProtocol:
http://code.google.com/p/selenium/wiki/JsonWireProtocol
The chrome diver protocol provides a method to maximize the window:
/session/:sessionId/window/:windowHandle/maximize,
but this command is not used in selenium-java. This means you also send the command to chrome yourself. Once I did this it works.
Chrome driver already support:
Java:
webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
For me, none of the solutions above worked when working with Selenium Web Driver C# + Chrome:
window.resizeTo(1024, 768); - I want to use the whole screen
--start-maximized - it is ignored
driver.manage().window().maximize(); - does not work because it requires some extension and I am not allowed to use Chrome extensions
I managed to get it working using InputSimulator:
var inputSim = new InputSimulator();
// WinKey + UP = Maximize focused window
inputSim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.UP);
You can try with this code to maximize chrome window.
ChromeOptions options = new ChromeOptions();
options.addArguments("--window-size=1920,1080");
WebDriver driver = new ChromeDriver(options);

Categories

Resources