i made a Java application whose purpose is to offer a Print Preview for PS files.
My program uses Ghostscript and Ghost4J to load the Post Script file and produces a list of Images (one for each page) using the SimpleRenderer.render method. Then using a simple JList i show only the image corresponding to the page the user selected in JList.
This worked fine until a really big PS file occurred, causing an OutOfMemoryError when executing the code
PSDocument pdocument = new PSDocument(new File(filename));
I know that is possibile to read a file a little at a time using InputStreams, the problem is that i can't think of a way to connect the bytes that i read with the actual pages of the document.
Example, i tried to read from PS file 100 MB at a time
int buffer_size = 100000000;
byte[] buffer = new byte[buffer_size];
FileInputStream partial = new FileInputStream(filename);
partial.read(buffer, 0, buffer_size);
document.load(new ByteArrayInputStream(buffer));
SimpleRenderer renderer = new SimpleRenderer();
//how many pages do i have to read?
List<Image> images = renderer.render(document, firstpage ??, lastpage ??);
Am i missing some Ghost4J functionality to read partially a file?
Or has someone other suggestions / approaches about how to solve this problem in different ways?
I am really struggling
I found out I can use Ghost4J Core API to retrieve from a Post Script file a reduced set of pages as Images.
Ghostscript gs = Ghostscript.getInstance();
String[] gsArgs = new String[9];
gsArgs[0] = "-dQUIET";
gsArgs[1] = "-dNOPAUSE";
gsArgs[2] = "-dBATCH";
gsArgs[3] = "-dSAFER";
gsArgs[4] = "-sDEVICE=display";
gsArgs[5] = "-sDisplayHandle=0";
gsArgs[6] = "-dDisplayFormat=16#804";
gsArgs[7] = "-sPageList="+firstPage+"-"+lastPage;
gsArgs[8] = "-f"+filename;
//create display callback (capture display output pages as images)
ImageWriterDisplayCallback displayCallback = new ImageWriterDisplayCallback();
//set display callback
gs.setDisplayCallback(displayCallback);
//run PostScript (also works with PDF) and exit interpreter
try {
gs.initialize(gsArgs);
gs.exit();
Ghostscript.deleteInstance();
} catch (GhostscriptException e) {
System.out.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
return displayCallback.getImages(); //return List<Images>
This solve the problem of rendering page as images in the preview.
However, i could not find a way to use Ghost4J to know total number of pages of PS file (in case the file is too big for opening it with Document.load()).
So, i am still here needing some help
I read a lot of options related with the way to open new windows with Selenium. All the questions and answers are from a few years ago and maybe that's why they are not working to me. And that's why I would like to open this question again.
My first approach was using javascript action:
((JavascriptExecutor) getDriver()).executeScript("window.open('','NewWindow');");
My issue here is the different result in Firefox and Chrome. Firefox opens a new window and Chrome opens a new tab. This means that my test case is not working as expected if I executed in different browsers.
After that I think about a different approach. If I send the shortcut to open a new tab maybe both browsers will work with the same behavior. And here started my nightmare. None of the next options open anything in the current Chrome and Firefox versions:
Send keys concatenate the shortcut:
getDriver().findElement(By.xpath(".//body")).sendKeys(Keys.COMMAND+"T");
Send keys multiple keys sequence:
getDriver().findElement(By.xpath(".//body")).sendKeys(Keys.COMMAND,"T");
Send Keys chord
getDriver().findElement(By.xpath(".//body")).sendKeys(Keys.chord(Keys.COMMAND + "T"));
Using actions
final Actions builder = new Actions(getDriver());
builder.keyDown(Keys.COMMAND).sendKeys("T").perform();
I'm thinking about try with the COMMAND key Down click on any link, but maybe there is an other easy way to open a new tab in different browsers. And this is my question, do you now an efficient way to open a new tab, not a new window, in different browsers with the same action?
ADITIONAL INFORMATION
Selenium version -> 3.141.59
Chrome version -> 79.0.3945.79
Firefox version -> 70.0.1
Thank you in advance.
This may be help you:-
Using JavascriptExecutor:-
Open new blank window:-
((JavascriptExecutor)driver).executeScript("window.open('about:blank','_blank');");
Open new window with specific url:
((JavascriptExecutor)driver).executeScript("window.open('http://www.yahoo.com','_blank');");
Using Robot class:-
Robot class in Selenium is used for simulating keyboard and mouse events. So, in order to open a new tab, we can simulate the keyboard event of pressing Control Key followed by âtâ key of the keyboard. After the new tab gets opened, we need to switch focus to it otherwise the driver will try to perform the operation on the parent tab only.
For switching focus, we will be using getWindowHandles() to get the handle of the new tab and then switch focus to it.
//Use robot class to press Ctrl+t keys
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);
//Implicit Wait
//driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
Thread.sleep(2000);
//Switch focus to new tab
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
//Launch URL in the new tab
driver.get("http://google.com");*/
Two approach of Robot Class to Open url in new tab using selenium
public class NewTab
{
public static void main(String[] args) throws InterruptedException, AWTException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.facebook.com/");
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_T);
Set<String> tabs = (Set<String>)driver.getWindowHandles();
for(String tab : tabs)
{
driver.switchTo().window(tab);
System.out.println(driver.getTitle());
if(driver.getTitle().contains("New Tab"))
driver.get("http://www.google.com/");
}
}
}
Another way, without using the for loop
public class NewTab {
public static void main(String[] args) throws InterruptedException, AWTException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_T);
String Base = driver.getWindowHandle();
Set<String> tabs = (Set<String>)driver.getWindowHandles();
tabs.remove(Base);
driver.switchTo().window(tabs.toArray()[0].toString());
driver.get("http://www.facebook.com/");
}
}
Please try below code.
I didn't use javascript.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);
As a user asked how I finally solved this, my solution was this:
// Save the current window reference
final String parentWindow = driver.getWindowHandle();
// Look for the element I would like to click
final WebElement elem = driver.findElement(By.xpath(xpath));
// Create an action to be performed
final Actions builder = new Actions(driver);
// The OSKEY is a global variable where depending on the OS is saved CMD or CTR
// With the special key chord, the program clicks on the element
builder.keyDown(OSKEY).click(elem).perform();
For me is working without browser problems.
I am working on 2 URLS . I need to open the first URL ,perform some action and open the second URL.
openURL1()
{
perform action
}
openURL2()
{
perform action
}
switch back to URL1
when I use driver.get or driver.navigate , URL1 gets closed. Is there anyway to retain the window with URL1 while opening URL2?
I am working with selenium and JAVA
If the second tab is not opened through an action that is performed in first tab, then you can use two driver objects, so that you'll have control of both the browsers with different driver objects.
WebDriver driver = new ChromeDriver();
driver.get("https://news.ycombinator.com");
WebDriver driver1 = new ChromeDriver();
driver1.get("https://www.google.com");
By this approach you can use driver to control URL1 and driver1 to control URL2.
Here is the Answer to your Question:
Here is the working code block which opens the URL http://www.google.com, prints Working on Google on the console, opens http://facebook.com/ in a new tab, prints Working on Facebook in the console, closes the tab which opened the URL http://facebook.com/, gets you back to the tab which opened the URL http://www.google.com and finally closes it.
System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
String first_tab = driver.getWindowHandle();
System.out.println("Working on Google");
((JavascriptExecutor) driver).executeScript("window.open('http://facebook.com/');");
Set<String> s1 = driver.getWindowHandles();
Iterator<String> i1 = s1.iterator();
while(i1.hasNext())
{
String next_tab = i1.next();
if (!first_tab.equalsIgnoreCase(next_tab))
{
driver.switchTo().window(next_tab);
System.out.println("Working on Facebook");
driver.close();
}
}
driver.switchTo().window(first_tab);
driver.close();
Let me know if this Answers your Question.
You may use javascript to open new tab
(JavascriptExecutor(driver)).executeScript("window.open();");
How can I open a new tab in the existing Firefox browser using Selenium WebDriver (a.k.a. Selenium 2) in Java?
Just for anyone else who's looking for an answer in Ruby, Python, and C# bindings (Selenium 2.33.0).
Note that the actual keys to send depend on your OS. For example, Mac uses CMD + T, instead of Ctrl + T.
Ruby
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
driver.get('http://stackoverflow.com/')
body = driver.find_element(:tag_name => 'body')
body.send_keys(:control, 't')
driver.quit
Python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")
body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.CONTROL + 't')
driver.close()
C#
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace StackOverflowTests {
class OpenNewTab {
static void Main(string[] args) {
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://stackoverflow.com/");
IWebElement body = driver.FindElement(By.TagName("body"));
body.SendKeys(Keys.Control + 't');
driver.Quit();
}
}
}
The code below will open the link in a new tab.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);
The code below will open an empty new tab.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);
Why not do this
driver.ExecuteScript("window.open('your url','_blank');");
To open new tab using JavascriptExecutor,
((JavascriptExecutor) driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
Will control on tab as according to index:
driver.switchTo().window(tabs.get(1));
Driver control on main tab:
driver.switchTo().window(tabs.get(0));
As of selenium >= 4.0, there is no need for javascript or send_keys workarounds. Selenium 4 provides a new API called newWindow that lets you create a new window (or tab) and automatically switches to it. Since the new window or tab is created in the same session, it avoids creating a new WebDriver object.
Python
Open new tab
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.window import WindowTypes
driver.switch_to.new_window(WindowTypes.TAB)
Open new window
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.window import WindowTypes
driver.switch_to.new_window(WindowTypes.WINDOW)
Java
Open new window
driver.get("https://www.google.com/");
// Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW);
// Opens LambdaTest homepage in the newly opened window
driver.navigate().to("https://www.lambdatest.com/");
Open new tab
driver.get("https://www.google.com/");
// Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.TAB);
// Opens LambdaTest homepage in the newly opened tab
driver.navigate().to("https://www.lambdatest.com/")
You can use the following code using Java with Selenium WebDriver:
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
By using JavaScript:
WebDriver driver = new FirefoxDriver(); // Firefox or any other Driver
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.open()");
After opening a new tab it needs to switch to that tab:
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
To open a new window in Chrome Driver.
// The script that will will open a new blank window
// If you want to open a link new tab, replace 'about:blank' with a link
String a = "window.open('about:blank','_blank');";
((JavascriptExecutor)driver).executeScript(a);
For switching between tabs, read here.
Almost all answers here are out of date.
(Ruby examples)
WebDriver now has support for opening tabs:
browser = Selenium::WebDriver.for :chrome
new_tab = browser.manage.new_window
Will open a new tab. Opening a window has actually become the non-standard case:
browser.manage.new_window(:window)
The tab or window will not automatically be focussed. To switch to it:
browser.switch_to.window new_tab
Try this for the Firefox browser.
/* Open new tab in browser */
public void openNewTab()
{
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(0));
}
To open a new tab in the existing Chrome browser using Selenium WebDriver you can use this code:
driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");
string newTabInstance = driver.WindowHandles[driver.WindowHandles.Count-1].ToString();
driver.SwitchTo().Window(newTabInstance);
driver.Navigate().GoToUrl(url);
The below code will open the link in a new window:
String selectAll = Keys.chord(Keys.SHIFT, Keys.RETURN);
driver.findElement(By.linkText("linkname")).sendKeys(selectAll);
I had trouble opening a new tab in Google Chrome for a while.
Even driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t"); didn't work for me.
I found out that it's not enough that Selenium has focus on driver. Windows also has to have the window in the front.
My solution was to invoke an alert in Chrome that would bring the window to front and then execute the command. Sample code:
((JavascriptExecutor)driver).executeScript("alert('Test')");
driver.switchTo().alert().accept();
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(0));
// To open a new tab in an existing window
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
How can we open a new, but more importantly, how do we do stuff in that new tab?
Webdriver doesn't add a new WindowHandle for each tab, and only has control of the first tab. So, after selecting a new tab (Control + Tab Number) set .DefaultContent() on the driver to define the visible tab as the one you're going to do work on.
Visual Basic
Dim driver = New WebDriver("Firefox", BaseUrl)
' Open new tab - send Control T
Dim body As IWebElement = driver.FindElement(By.TagName("body"))
body.SendKeys(Keys.Control + "t")
' Go to a URL in that tab
driver.GoToUrl("YourURL")
' Assuming you have m tabs open, go to tab n by sending Control + n
body.SendKeys(Keys.Control + n.ToString())
' Now set the visible tab as the drivers default content.
driver.SwitchTo().DefaultContent()
I am using Selenium 2.52.0 in Java and Firefox 44.0.2. Unfortunately none of the previous solutions worked for me.
The problem is if I a call driver.getWindowHandles() I always get one single handle. Somehow this makes sense to me as Firefox is a single process and each tab is not a separate process. But maybe I am wrong. Anyhow, I try to write my own solution:
// Open a new tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
// URL to open in a new tab
String urlToOpen = "https://url_to_open_in_a_new_tab";
Iterator<String> windowIterator = driver.getWindowHandles()
.iterator();
// I always get handlesSize == 1, regardless how many tabs I have
int handlesSize = driver.getWindowHandles().size();
// I had to grab the original handle
String originalHandle = driver.getWindowHandle();
driver.navigate().to(urlToOpen);
Actions action = new Actions(driver);
// Close the newly opened tab
action.keyDown(Keys.CONTROL).sendKeys("w").perform();
// Switch back to original
action.keyDown(Keys.CONTROL).sendKeys("1").perform();
// And switch back to the original handle. I am not sure why, but
// it just did not work without this, like it has lost the focus
driver.switchTo().window(originalHandle);
I used the Ctrl + T combination to open a new tab, Ctrl + W to close it, and to switch back to original tab I used Ctrl + 1 (the first tab).
I am aware that mine solution is not perfect or even good and I would also like to switch with driver's switchTo call, but as I wrote it was not possible as I had only one handle. Maybe this will be helpful to someone with the same situation.
How to open a new tab using Selenium WebDriver with Java for Chrome:
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-extensions");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.navigate().to("https://google.com");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);
The above code will disable first extensions and using the robot class, a new tab will open.
This line of code will open a new browser tab using Selenium WebDriver:
((JavascriptExecutor)getDriver()).executeScript("window.open()");
Java
I recommend using JavascriptExecutor:
Open new blank window:
((JavascriptExecutor) driver).executeScript("window.open()");
Open new window with specific URL:
((JavascriptExecutor) driver).executeScript("window.open('https://google.com')");
Following import:
import org.openqa.selenium.JavascriptExecutor;
Check this complete example to understand how to open multiple tabs and switch between the tabs and at the end close all tabs.
public class Tabs {
WebDriver driver;
Robot rb;
#BeforeTest
public void setup() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Anuja.AnujaPC\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://qaautomated.com");
}
#Test
public void openTab() {
// Open tab 2 using CTRL + T keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
// Open URL In 2nd tab.
driver.get("http://www.qaautomated.com/p/contact.html");
// Call switchToTab() method to switch to the first tab
switchToTab();
// Call switchToTab() method to switch to the second tab.
switchToTab();
}
public void switchToTab() {
// Switching between tabs using CTRL + tab keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
// Switch to current selected tab's content.
driver.switchTo().defaultContent();
}
#AfterTest
public void closeTabs() throws AWTException {
// Used Robot class to perform ALT + SPACE + 'c' keypress event.
rb = new Robot();
rb.keyPress(KeyEvent.VK_ALT);
rb.keyPress(KeyEvent.VK_SPACE);
rb.keyPress(KeyEvent.VK_C);
}
}
This example is given by this web page.
There are 3 ways to do this. In below example I am doing following steps to open the facebook in new tab,
Launching https://google.com
Searching for facebook text and getting the facebook URL
Opening facebook in different tab.
Solution#1: Using window handles.
driver = new ChromeDriver(options);
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(#href,'facebook.com')])[1]")).getAttribute("href");
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get(facebookUrl);
Solution#2: By creating new driver instance. It's not recommended but it is also a possible way to do this.
driver = new ChromeDriver(options);
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(#href,'facebook.com')])[1]")).getAttribute("href");
/*Create an another instance of driver.*/
driver = new ChromeDriver(options);
driver.get(facebookUrl);
Solution#3: Using Selenium 4
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(#href,'facebook.com')])[1]")).getAttribute("href");
driver.switchTo().newWindow(WindowType.TAB);
driver.navigate().to(facebookUrl);
If you need to open a specific link in a new tab, you can send the shortcut directly to the link like so:
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
driver.findElement(By.xpath("//a[strong[.='English']]")).sendKeys(selectLinkOpeninNewTab);
Here is an runnable example
If you need to open a new tab and want to choose which link is opened immediately in said tab, you can use JavaScriptExecutor like so:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open('https://www.wikipedia.org/', '_blank');");
Here is a runnable case that uses JSE
In new versions of selenium for java, they added a method to create a new tab:
driver.switchTo().newWindow(WindowType.TAB);
or a new window:
driver.switchTo().newWindow(WindowType.WINDOW);
here is the link to an example on the official repo
To open a new tab in the existing Firefox browser using Selenium WebDriver
FirefoxDriver driver = new FirefoxDriver();
driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL,"t");
Actions at=new Actions(wd);
at.moveToElement(we);
at.contextClick(we).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
The same example for Node.js:
var webdriver = require('selenium-webdriver');
...
driver = new webdriver.Builder().
withCapabilities(capabilities).
build();
...
driver.findElement(webdriver.By.tagName("body")).sendKeys(webdriver.Key.COMMAND + "t");
This code is working for me (Selenium 3.8.1, chromedriver 2.34.522940, and Chrome 63.0):
public void openNewTabInChrome() {
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.linkText("Gmail"));
Actions actionOpenLinkInNewTab = new Actions(driver);
actionOpenLinkInNewTab.moveToElement(element)
.keyDown(Keys.CONTROL) // MacOS: Keys.COMMAND
.keyDown(Keys.SHIFT).click(element)
.keyUp(Keys.CONTROL).keyUp(Keys.SHIFT).perform();
ArrayList<String> tabs = new ArrayList(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get("http://www.yahoo.com");
//driver.close();
}
Question: How can I open a new tab using Selenium WebDriver with Java?
Answer: After a click on any link, open a new tab.
If we want to handle a newly open tab then we have need to handle tab using the .switchTo().window()
command.
Switch to a particular tab, and then perform an operation and switch back to into the parent tab.
package test;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Tab_Handle {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "geckodriver_path");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
// Store all currently open tabs in Available_tabs
ArrayList<String> Available_tabs = new ArrayList<String>(driver.getWindowHandles());
// Click on link to open in new tab
driver.findElement(By.id("Url_Link")).click();
// Switch newly open Tab
driver.switchTo().window(Available_tabs.get(1));
// Perform some operation on Newly open tab
// Close newly open tab after performing some operations.
driver.close();
// Switch to old(Parent) tab.
driver.switchTo().window(Available_tabs.get(0));
}
}
Selenium doesn't support opening new tabs. It only supports opening new windows. For all intents and purposes a new window is functionally equivalent to a new tab anyway.
There are various hacks to work around the issue, but they are going to cause you other problems in the long run.
If you want to open the new tab you can use this
((JavascriptExecutor) getDriver()).executeScript("window.open()");
If you want to open the link from the new tab you can use this
With JavascriptExecutor:
public void openFromNewTab(WebElement element){
((JavascriptExecutor)getDriver()).executeScript("window.open('"+element.getAttribute("href")+"','_blank');");
}
With Actions:
WebElement element = driver.findElement(By.xpath("your_xpath"));
Actions actions = new Actions(driver);
actions.keyDown(Keys.LEFT_CONTROL)
.click(element)
.keyUp(Keys.LEFT_CONTROL)
.build()
.perform();
can anyone tell me how I can capture a webpage using Java Selenium? With an example....
See here: Capturing screenshots from remote Selenium RC.
In essence:
"To solve this you can use the captureScreenshotToString and captureEntirePageScreenshotToString commands, which return a Base64 encoded String of the screenshot, which you can then decode and save to disk on your testrunner machine."
I think this is what you are looking for. But try to be mores specific if it is not.
captureEntirePageScreenshot (
filename,kwargs )
Saves the entire contents of the current window canvas to a PNG file.
Contrast this with the
captureScreenshot command, which
captures the contents of the OS
viewport (i.e. whatever is currently
being displayed on the monitor), and
is implemented in the RC only.
Currently this only works in Firefox
when running in chrome mode, and in IE
non-HTA using the EXPERIMENTAL
"Snapsie" utility. The Firefox
implementation is mostly borrowed from
the Screengrab! Firefox extension.
Please see http://www.screengrab.org
and http://snapsie.sourceforge.net/
for details.
Arguments:
* filename - the path to the file to persist the screenshot as. No
filename extension will be appended by
default. Directories will not be
created if they do not exist, and an
exception will be thrown, possibly by
native code.
* kwargs - a kwargs string that modifies the way the screenshot
is captured. Example:
"background=#CCFFDD" . Currently valid
options:
background
the background CSS for the HTML document. This may be useful
to set for capturing screenshots of
less-than-ideal layouts, for example
where absolute positioning causes the
calculation of the canvas dimension to
fail and a black background is exposed
(possibly obscuring black text).
public static void getSnapShot(WebDriver driver, String event) {
{
try {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage originalImage = ImageIO.read(scrFile);
//int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
jpeg.setAlignment(Image.MIDDLE);
++index;
} catch (Exception e) {
e.printStackTrace();
}
}
}
I like to use PhantomJS driver for taking screenshots.
public class Test {
public static void main(String[] args) {
//PhantomJS headless driver
File file = new File("D:\\Webdriver\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
WebDriver driver = new PhantomJSDriver();
//Set Size here
driver.manage().window().setSize(new Dimension(1600,900));
//To wait until the element get visible or invisible.
WebDriverWait wait = new WebDriverWait(driver, 25);
//To access url.
driver.get("https://www.google.co.in");
//For wait until the element get visible.
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("lst-ib")));
File shot=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(shot, new File("D:\\Webdriver\\Capture.jpg"));
}
}
It takes full page screenshot of chrome webpage.
System.setProperty("webdriver.chrome.driver", "F:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
String baseUrl = "https://www.google.co.in";
driver.get(baseUrl);
String fullscreen =Keys.chord(Keys.F11);
driver.findElement(By.cssSelector("body")).sendKeys(fullscreen);
TakesScreenshot scrShot =((TakesScreenshot)driver);
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
File DestFile=new File("F://test.png");
FileUtils.copyFile(SrcFile, DestFile);
driver.close();
I see a lot of answers explaining screenshots, but just incase you are asking how to get the entire source of the page use the following method:
String pageSource = driver.getPageSource();
Here is a runnable example.