C#: How to send key combination in selenium's Keyboard.SendKeys - c#

I'm using Selenium 2 on Windows to automate firefox. I tried to send 'Alt+Esc' to the browser to minimise it on start. However firefox keeps typing the '{%ESC}' in its address bar. What should I do? thanks.
using (driver = new FirefoxDriver(firefoxProfile))
{
driver.Keyboard.SendKeys("{%ESC}");
}

I use this to open a new window (with the keyboard input) and it works just fine
IWebDriver driver = new FirefoxDriver();
Actions action = new Actions(driver);
action.SendKeys(OpenQA.Selenium.Keys.Control + "n").Build().Perform();

I prefer:
element.SendKeys(Keys.Control + "a");
Now you can focus on the element and not only on the webdriver

Sending regular key use SendKeys("ab12#$").
Sending a modifier key (Keys.Shift, Keys.Control, or Keys.Alt) use
.[KeyUp\keyDown]([OpenQA.Selenium.Keys.Control\OpenQA.Selenium.Keys.Alt...])
And you can combine them as needed:
action.KeyDown(OpenQA.Selenium.Keys.Shift).SendKeys("ThisWillBePrintedCAPS").KeyUp(OpenQA.Selenium.Keys.Shift).SendKeys("ThisWillBePrintedRegular").Build().Perform();

Related

How to set the download folder for Edge in Selenium?

I am writing automated tests using Selenium. I want to set the download directory in Edge so that I can download files as part of my test. There is an EdgeOptions object that I can provide when creating the EdgeDriver, but I don't know what to set on the EdgeOptions.
I know the equivalent of how to do this in Chrome
chromeOptions.AddUserProfilePreference("download.default_directory", #"C:\temp")
and Firefox
firefoxOptions.SetPreference("browser.download.dir", #"C:\temp")
But, how do I do the same thing in Edge? And get it to download automatically without a save prompt?
As #Prany already mentioned, probably there is no way to set download automatically. And if I right understood, you want to handle with native window dialogue, when you are clicking on download button. Selenium cannot interact with native windows, but you can use this framework. The sample code would be like this:
// Press the A Key Down
KeyboardSimulator.KeyDown(Keys.A);
// Let the A Key back up
KeyboardSimulator.KeyUp(Keys.A);
// Press A down, and let up (same as two above)
KeyboardSimulator.KeyPress(Keys.A);
// Simulate (Ctrl + C) shortcut, which is copy for most applications
KeyboardSimulator.SimulateStandardShortcut(StandardShortcut.Copy);
// This does the same as above
KeyboardSimulator.KeyDown(Keys.Control);
KeyboardSimulator.KeyPress(Keys.C);
KeyboardSimulator.KeyUp(Keys.Control);
So you can simulate Ctrl + V keyboard action and Enter action. Hope it helps.
You can do this for Edge like this:
// hide driver Console? true/false
EdgeDriverService service = EdgeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true; // hide Console
// change Standard-Download-Path
EdgeOptions options = new EdgeOptions();
var downloadDirectory = "C:\temp";
// Setting custom download directory
options.AddUserProfilePreference("download.default_directory", downloadDirectory);
// start Selenium Driver:
webdriver = new EdgeDriver(service, options);
// max. Window
webdriver.Manage().Window.Maximize();

How to use Selenium WebDriver to reset the zoom to default on Chrome?

How can I reset Chrome's zoom level to Default(100%) using Selenium WebDriver? It's really easy to do using keyboard keys "Ctrl + 0".
However, when I try to emulate this using WebDriver, I can't get anything to work. Here is what I tried without success:
[TestMethod]
public void ZoomToDefaultLevelWithChrome()
{
var driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://www.ultimateqa.com");
var actions = new Actions(driver);
var browser = (IJavaScriptExecutor)driver;
var html = driver.FindElement(By.TagName("html"));
//None of these work
actions.SendKeys(Keys.Control).SendKeys(Keys.Add).Perform();
actions.KeyDown(Keys.Control).SendKeys(Keys.NumberPad0).Perform();
//actions.KeyDown(Keys.Control).SendKeys(Keys.NumberPad0).Perform();
//actions.KeyDown(Keys.Control).SendKeys(html, "0").Perform();
actions.KeyUp(Keys.Control);
actions.KeyDown(Keys.Control).Perform();
actions.SendKeys(html, "0").Perform();
actions.SendKeys(html, Keys.NumberPad0).Perform();
actions.SendKeys(Keys.NumberPad0).Perform();
browser.ExecuteScript("document.body.style.zoom = '1.0'");
browser.ExecuteScript("document.body.style.transform='scale(1.0)';");
browser.ExecuteScript("document.body.style.zoom='100%';");
}
The first 2 solutions from here don't work in C#: Selenium webdriver zoom in/out page content
Also, this doesn't work in Chrome even though it might in other browsers: selenium vba code to zoom out webpage to 60%
Can you try the below. This should work.
((IJavaScriptExecutor)driver).executeScript("document.body.style.zoom='100%';");
I have also encountered this problem, a work around I found was good was setting the the resolution capability
capability.SetCapability("resolution", 1920x1080);

Open link in new tab selenium c#

I am writing a program to run videos listed on my site for testing purpose and here what I need is to run videos in different tabs of the same browser window.
I have hundred video urls in the List videoLinks = getVideoUrls();
and now what I need is to execute these videos 5 at a time.
ChromeDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://www.withoutabox.com" + videoLink);
If I go the above way then for all videos I will have to create a new ChromeDriver object. I want to use single chrome browser object.
I have tried this
IWebElement body = driver.FindElement(By.TagName("body"));
body.SendKeys(Keys.Control + "t");
it only adds a new tab but not open a link there.
Please let me know how should I go around it. I have googled but couldn't find my solution so thought to ask for help.
Try this:
public void SwitchToTab(object pageId)
{
webDriver.SwitchTo().Window(pageId.ToString());
}
You can use CurrentWindowHandle to find current tab.
webDriver.CurrentWindowHandle;
For your scenario I'm using that code:
public IPageAdapter OpenNewTab(string url)
{
var windowHandles = webDriver.WindowHandles;
scriptExecutor.ExecuteScript(string.Format("window.open('{0}', '_blank');", url));
var newWindowHandles = webDriver.WindowHandles;
var openedWindowHandle = newWindowHandles.Except(windowHandles).Single();
webDriver.SwitchTo().Window(openedWindowHandle);
return new SeleniumPage(webDriver);
}
Update
Window open create new popup. By default this option can be blocked by browser settings. Disable popup blocking in your browser manually.
To check this, open js console in your browser and try to execute command window.open('http://facebook.com', '_blank');
If new window open successfully than everythng is OK.
You can also create your chrome driver with specific setting. Here is my code:
var chromeDriverService = ChromeDriverService.CreateDefaultService();
var chromeOptions = new ChromeOptions();
chromeOptions.AddUserProfilePreference("profile.default_content_settings.popups", 0);
return new ChromeDriver(chromeDriverService, chromeOptions, TimeSpan.FromSeconds(150));
Here is a simple solution for open a new tab in seleneium c#:
driver.Url = "http://www.gmail.net";
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("window.open();");

Selenium webdriver: IE 11 sendKeys - select all(Ctrl+A) text in input (textbox)

I have method to select text using (Ctrl+A) which I use in automated tests.
public static void SelectText(IWebElement input)
{
Actions actions = new Actions(driver);
actions.Click(input).SendKeys(Keys.Control + "a").Perform();
}
In Chrome and Firefox method SelectText (working). But in IE 11 is not working.
In IE it only types "a".
For example: In input is text "lorem ipsum". In IE this method appends 'a' to end of the value "lorem ipsuma".
My configuration:
Windows 8.1, Selenium version 2.46.0, IEDriverServer.exe (x86 version).
IE initialization
InternetExplorerOptions ieOptions = new InternetExplorerOptions();
ieOptions.EnableNativeEvents = false;
IWebDriver driver = new InternetExplorerDriver(ieOptions);
How can I fix it?
I'm using a browser switch, when running for IE11 I use the following code to select all:
input.SendKeys(""); // focus element
SendKeys.SendWait ("^a"); // use windows to send input
Instead of that try using ASCII Code and use Build().Perform() isntead of Perform() alone
char c = '\u0001'; // ASCII code 1 for Ctrl-A
actions.Click(input).SendKeys(Convert.ToString(c)).Build().Perform();
In Internet Explorer this works for me
Actions actions = new Actions(_driver);
actions.Click(IWebElement);
actions.Click(cellProjectName).SendKeys("GU" + "Project" + "-" + consecutiveProjects).Perform();
in C#
I'm using .NET, and this is what worked for me:
input.SendKeys(Keys.Control & "a")

Selenium 2.0 WebDriver Advcanced Interactions DoubleClick Help (c#)

So within my selenium regression tests, I've been trying to double click on a calendar to make a new appt. I have attempted to use the doubleClick(); method within the advanceduserinteractions library, but there is an issue; the two clicks aren't fast enough/close enough together to fire an actual double-click! Has anybody found a way to deal with this in their testing?
This code works for me!
Actions action = new Actions(driver);
action.doubleClick(myElemment);
action.perform();
Here is the Java equivalent. This code will blindly open the first event. You could add some logic to open a specific event etc. This code works! (tested with 2.12)
List<WebElement> events = driver.findElements(By.cssSelector("div.dv-appointment"));
for(WebElement event:events){
WebElement body = event.findElement(By.cssSelector("div.body"));
if(!body.getText().isEmpty()) //or open a known event
{
System.out.println(body.getText()); //open the first event
Actions builder = new Actions(driver);
Action doubleClick = builder.doubleClick(event)
.build();
doubleClick.perform();
break;
}
}
Do not forget "using"
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Support.UI;
//create Actions object
Actions builder = new Actions(driver);
//create a chain of actions
builder.DoubleClick().Build().Perform();
http://selenium-interview-questions.blogspot.ru/2014/03/how-to-double-click-on-web-element.html
I too had the problem where Selenium's doubleclick event works in Firefox but has no effect in Chrome. Upgrading to Selenium didn't help; I already have the latest version. (My environment is Ubuntu 14.04, Python 2.7.6, Selenium 2.44.0, Firefox 35.0, Chrome 40.0.2214.91.)
I'm not sure why CBRRacer's answer was downvoted. I successfully worked around the problem by using two click events. This works in both Firefox and Chrome. There are two ways do to it, and both worked for me.
The first way:
elem = driver.find_element_by_css_selector('#myElement')
elem.click()
elem.click()
The second way:
elem = driver.find_element_by_css_selector('#myElement')
actions = webdriver.ActionChains(driver)
actions.click(elem).click(elem).perform()
I quite like the approach used here, particularly queuing the actions first, then performing, since that allows repeated application of the actionchain.
http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.common.action_chains.ActionChains
From the documentation example linked:
menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
actions = ActionChains(driver)
actions.move_to_element(menu)
actions.click(hidden_submenu)
actions.perform()
have you tried catching the IWebElement and then clicking it twice?
IWebElement element = driver.FindElement(By.Id("yourID"));
element.Click();
element.Click();
I don't know if this would give you the desird functionality or not but I know that when I execute a click event like the one above it runs as close as a double click from an actual user.
The other option is to reference the ThoughtWorks.Selenium.Core, however the only downside of this is that I'm not sure it plays well with the current IWebDriver I think it needs it's own instantiation of the IWebDriver.

Categories