Reputation: 1
I am still new to Selenium test world, and I am currently using Selenium ChromeDriver for testing.
Here is what I am trying to accomplish, with no success:
1 - I have ~50 opened tabs in Chrome and I want to press F9 on on them all at one time
2 - After pressing F9 to all tabs, if certain text appears on the page (No results), then close the tab.
I hope someone can help at either of these two features.
Thanks in advance.
Upvotes: 0
Views: 526
Reputation: 5909
There's no way (that I am aware of) to send a key press to multiple window handles at once (each tab is called a window handle in Selenium), but you can loop through the windows and try to use some Actions
class to send F9 key press to each page, then check for your desired text.
You will need to utilize Driver.WindowHandles
to get a list of current open tabs, and Driver.SwitchTo().Window()
to change the focus between tabs. Actions
class can simulate sending the F9 key to the current window. Driver.Close()
will close an existing tab.
Lastly, WebDriverWait
will be used to wait for 'No Results' text to populate before the code evaluates whether or not the current tab should be closed. WebDriverWait
will throw a TimeoutException
if the desired element does not appear on the page within the specified time parameter, so we wrap WebDriverWait
in a try
/ catch
block to handle scenarios where 'No Results' both exists, and does not exist.
The following code sample in C# should get you started:
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
// given you have 50 tabs open already
// get window handles -- this is a List<string> with length 50, one for each tab
var handles = Driver.WindowHandles;
// iterate window handles, switch to the window, and send F9 key
foreach (var window in handles)
{
// switch to the window
Driver.SwitchTo().Window(window);
// send F9 key press to the current tab
new Actions(Driver).SendKeys(Keys.F9).Perform();
// wait for 'No Results' text
try
{
new WebDriverWait(Driver, TimeSpan.FromSeconds(30)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[contains(text(), 'No Results')]")));
// if TimeoutException is not thrown, then No Results text exists. so close the tab
Driver.Close();
}
catch (TimeoutException)
{
// case: 'No Results' text does not exist. do not close the tab.
}
}
This is a very general outline, and will almost certainly require some modification on your end to get it working completely. For example, the XPath used in new WebDriverWait(Driver, TimeSpan.FromSeconds(30)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[contains(text(), 'No Results')]")));
may need to be tweaked to ensure the correct element displaying 'No Results' text is located. Hopefully this gets you started.
Upvotes: 1