chrome webdriver cannot open new tab - c#

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

Related

How to select Options-Button on specifig page C# Selenium

I try to select an option of a Button and found a working solution ;)
But i did not understand why the mostly posted standard will not work.
My solution is this line:
webdriver.FindElement(By.XPath("//select[#id='select-max-bars']/option[contains(text(), '200 000')]")).Click();
What i want to do:
Side: https://eatradingacademy.com/software/forex-historical-data/
Scroll a little down and Navigate to "Settings" (blue Text).
Here the Button for "Maximum bars" must be changed to 200.000.
Why will the Code just down not work for this?
Can anybody explain this for me?
Thank you
Here are the Side-Elements:
enter image description here
This is my not working code. The last 5 lines are the problem:
// Start driver
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = false; // hide Console
webdriver = new ChromeDriver(service);
webdriver.Manage().Window.Maximize();
webdriver.Navigate().GoToUrl("https://eatradingacademy.com/software/forex-historical-data/");
Thread.Sleep(1000);
// deny upcoming Request
webdriver.FindElement(By.Id("webpushr-deny-button")).Click();
// Navigate to Page (Link) = Settings
webdriver.SwitchTo().Frame(webdriver.FindElement(By.Id("data-app-frame")));
var statistics = webdriver.FindElement(By.XPath("//a[#class='nav-link panel-switch' and contains(text(), 'Settings')]"));
Actions actions = new Actions(webdriver);
actions.MoveToElement(statistics);
actions.Perform();
statistics.Click();
// Click Button "Reset"
webdriver.FindElement(By.Id("btn-reset-settings")).Click();
// for Test only: Button can be clicked
// //webdriver.FindElement(By.Id("select-max-bars")).Click();
// How to select the Option in the "Drop Down" Button "Maximum Bars" ?
// This here will not work for me:
// ###################################################################
SelectElement objSelect = new SelectElement(webdriver.FindElement(By.Id("select-max-bars")));
Thread.Sleep(15);
//objSelect.selectByText("200 000");
objSelect.SelectByValue("200000");

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?

selenium wait for flash page load (document.ready)

I want to make screenshot on webpage which is written in flash
For that I have this code:
ChromeOptions options = new ChromeOptions();
IWebDriver driver = new ChromeDriver(options);
...
// I'm clicking on button whicch opens new browser window
driver.FindElement(By.ClassName("click_me")).Click();
Thread.Sleep(1500);
//switch to new window
driver.SwitchTo().Window(driver.WindowHandles.Last());
//maximize it
driver.Manage().Window.Maximize();
//wait for load
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
//and then take screenshot
Screenshot sc = ((ITakesScreenshot)driver).GetScreenshot();
sc.SaveAsFile(String.Format(#"{0}\{1}.{2}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), Guid.NewGuid(), ScreenshotImageFormat.Png), ScreenshotImageFormat.Png);
Here works everything but wait for load. It takes a screenshot of loading screen. What can i do?
//wait for load
WaitForLoading(driver);
private void WaitForLoading(IWebDriver driver)
{
var javascriptExecutor = (IJavaScriptExecutor)driver;
_wait.Until(webDriver => javascriptExecutor.ExecuteScript("return document.readyState").ToString() == "complete");
}

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

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