Opening a new tab using Ctrl + click combination in Selenium Webdriver - javascript

I am attempting to use ctrl + click on a link to open it in a new tab. This is working fine in Chrome 58. Please find the code below:
action.keyDown(Keys.CONTROL).click(driver.findElement(By.xpath
("//section[#class='filmStrip__basic']//a[text()='En savoir
plus']"))).keyUp(Keys.CONTROL).build().perform();
I am using the same code on IE, Firefox and Safari but getting the following error:
Firefox 54: The link is getting open in the same tab.
IE 11: Nothing happening.. the control is moving to the next line
Safari: exception on action.keyDown-Unrecognized command
Help related to any one browser is also appreciated.
Thanks

As you are trying to click on a link which is within a <a> tag, instead of xpath you can use the linkText locator. Here is the sample code with opens the url http://www.google.com, verifies the Page Title, uses Actions class to click on the Gmail link to open https://accounts.google.com in a new tab.
String URL="http://www.google.com";
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get(URL);
System.out.println("Page Title is : "+driver.getTitle());
WebElement link = driver.findElement(By.linkText("Gmail"));
Actions newTab = new Actions(driver);
newTab.keyDown(Keys.CONTROL).click(link).keyUp(Keys.CONTROL).build().perform();
You can find a relevant Python based solution in How to open a link embed in web element in the main tab, in a new tab of the same window using Selenium Webdriver

Another way is to use javascript executor:
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.open('','_blank');");
As for your problem I had it too and didn't find anything usefull until I found this workaround.
I even tried: solution with ctrl + enter

try this way....
// specify chromedriver.exe directory path and replace in "driverPath"
String driverPath = "C:/Users......";
WebDriver driver;
System.setProperty("webdriver.chrome.driver", driverPath + "chromedriver.exe");
driver = new ChromeDriver();
System.out.println("lanuching 1st url in tab1");
driver.navigate().to(
"https://amazon.com");
System.out.println("lanuched 1st url in tab1");
Thread.sleep(30000);
((JavascriptExecutor) driver).executeScript(
"window.open('http://ebay.com');");
Thread.sleep(20000);
Set<String> allwh = driver.getWindowHandles();
System.out.println(allwh.size());
for (String v : allwh) {
System.out.println(v);
driver.switchTo().window(v);
String title = driver.getTitle();
System.out.println("2nd url in tab2" + title);

Related

Removing scrollbar from Selenium Screenshots

I'm getting screenshots of webpages using Chromedriver. My code works well.
I'm now attempting to remove the ugly scrollbars. Would it be possible to inject CSS into the page? I have seen a couple of similar questions, which do hint that this is possible ("You can also make Chromedriver open the url in a popup without scrollbars. You can do this using some Javascript.") but doesn't show how this is possible.
Has anybody got any idea as to how to do this?
IWebDriver driver = new ChromeDriver();
driver.Manage().Window.Size = new Size(1100, 1100);
driver.Navigate().GoToUrl("http://google.com/");
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
//Temp Img
string screenshot = ss.AsBase64EncodedString;
byte[] screenshotAsByteArray = ss.AsByteArray;
ss.SaveAsFile(fileNameTemp, ScreenshotImageFormat.Jpeg);
ss.ToString();
// Create a driver instance for chromedriver
IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
driver.Manage().Window.Size = new Size(1100, 1100);
driver.Navigate().GoToUrl(hehe[i]);
js.ExecuteScript("return document.body.style.overflow = 'hidden';");
This worked!

How to handle a new window in selenium when I opened it by javascript

Using selenium in internet explorer I have opened a new window with javascript code:
((JavascriptExecutor) driver).executeScript("windows.open('www.google.com')");
When I try to move to that new window selenium does not detect the window. At the time of printing the number of windows opened by the driver I only get 1:
Set<String> handlesSet = visor.getWindowHandles();
List<String> handlesList = new ArrayList<String>(handlesSet);
System.out.println("open windows: " + handlesList.size());
My question: ¿Is it possible to manage that new window opened from javascript?
Thank you.
It doesn't work because windows, it should window, without s:
((JavascriptExecutor) driver).executeScript("window.open('https://www.google.com')");
Don't forget to put full url with https://

How to print the page and close the Print window in selenium

Selenium fresher:
I used the following code in selenium to open the print window but it doesn't work
Keyboard keyboard = ((HasInputDevices)driver).getKeyboard();
keyboard.pressKey(Keys.ENTER);
keyboard.pressKey(Keys.chord(Keys.CONTROL, "p"));
And i used the following code to open the Print window and it works
((JavascriptExecutor) driver).executeScript("print()");
My Question is how to print the page and close the print window?
You can use the kiosk-printing chrome option to complete the print without interacting with print window.
Here is the snippet that you can use.
Java:
ChromeOptions options = new ChromeOptions();
options.addArguments("--kiosk-printing");
WebDriver driver = new ChromeDriver(options);
driver.get("https://google.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.print();");
Python:
options = webdriver.ChromeOptions()
options.add_argument('--kiosk-printing')
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://google.com")
driver.execute_script('window.print();')
You will see the print window for a fraction of seconds and then it will close automatically. Then you can see the printing job in your default printer.

Unable to click any link in the web page

I am using selenium webdriver to automate a web page. My selenium code is not identifying the link. I am getting the following error.
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
no such element: Unable to locate element:
{"method":"xpath","selector":"/html/body/font/font/b/a[2]"} (Session
info: chrome=44.0.2403.89)
This is the code i am using .
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver","C:\\Program Files (x86)\\Google\\Chrome\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("url");
driver.findElement(By.xpath("/html/body/font/font/b/a[2]")).click();
}
Thanks in advance
If you are getting NoSuchElementException as your provided exception, There are may be following reasons :-
May you are locating with incorrect xpath, So you need to share HTML for better locator solution.
May be when you are going to find element, it would not be present on the DOM, So you should implement WebDriverWait to wait until element visible and clickable as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement el = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Duty Office")));
el.click();
May be this element is inside any frame or iframe. If it is, you need to switch that frame or iframe before finding the element as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
//Find frame or iframe and switch
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("your frame id or name"));
//Now find the element
WebElement el = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Duty Office")));
el.click();
//Once all your stuff done with this frame need to switch back to default
driver.switchTo().defaultContent();
Hope it helps...:)
There are two possible situation
1) you might type wrong url
2) your expected element xpath is wrong.
please validate your xpath with
this tolol : https://chrome.google.com/webstore/detail/xpath-helper/hgimnogjllphhhkhlmebbmlgjoejdpjl?hl=en
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Program Files (x86)\Google\Chrome\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("Valid url");
driver.findElement(By.xpath("your valid XPATH")).click();
driver.close();
}

Disable Javascript in Selenium? Noscript doesn't seem to work

I am trying to disable javascript in selenium using noscript extension, as suggested here -->How to disable Javascript when using Selenium by JAVA?
But, it looks like it no longer works,
Here is what I have written :
FirefoxProfile profile = new FirefoxProfile();
File extPath = new File("noscript.xpi");
profile.addExtension(extPath);
//profile.setPreference("javascript.enabled", false);
WebDriver driver = new FirefoxDriver(profile);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://enable-javascript.com");
Even tried it by loading a profile that has javascript disabled, that doesn't seem to work either.
Code :
File profileDirectory = new File("Profiles/4hsi6txm.testing");
FirefoxProfile profile = new FirefoxProfile(profileDirectory);
DesiredCapabilities cap = DesiredCapabilities.firefox();
//
cap.setCapability(FirefoxDriver.PROFILE, profile);
WebDriver driver = new FirefoxDriver(cap);
driver.get("http://enable-javascript.com");
I am trying it on Firefox version-43.0.1 and selenium version-2.48.2
Any fix for this ?
Thanks :)

Categories