Take a Screenshot with RemoteWebDriver - java

Is there a way to get selenium screenshots with headers ? I've tried the code below but the screenshot does not have a header.
I have a test case that requires clicking a link and making sure the action must bring to a new tab, so as evidence I have to attach capture there are two tabs.
public static void main (String args[]) throws IOException {
DesiredCapabilities dc = new DesiredCapabilities();
RemoteWebDriver driver;
URL url = new URL("http://localhost:4444/wd/hub");
dc.setCapability(CapabilityType.BROWSER_NAME, BrowserType.CHROME);
dc.setCapability(CapabilityType.PLATFORM, "MAC");
driver = new RemoteWebDriver(url, dc);
driver.manage().window().maximize();
driver.get("https://google.com");
new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.name("q")));
File getImage = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(getImage, new File("/Users/path/screenshot.jpg"));
driver.quit();
}
Current result
Expected result

No you can't, the screenshot functionality in Selenium takes an image of the rendered DOM. The browser chrome (i.e. the the UI components of the browser rendered by the OS the browser is running on) is not part of the DOM so Selenium is unaware of it.
The next question is why do you want the browser chrome in your image? If you are just trying to find out the displayed URL (as your question implies) you can use the command driver.getCurrentUrl(); instead.

As #Ardesco suggested, it is not possible to take screenshot.
However i think you can use java.awt.Robot class to capture the screen. It takes the screenshot of the current screen.
Here's an snapshot of code for capturing screenshot using java.awt,
public void getScreenshot(int timeToWait) throws Exception {
Rectangle rec = new Rectangle(
Toolkit.getDefaultToolkit().getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, "jpg", setupFileNamePath());
}

Related

Is there any capabilities to set Firefox browser zoom level to some specific percent throughout script execution?

I'm using Firefox browser and i want to set the zoom level 90% while it executing the script.
I have tried to set using JavascriptExecutor like -
((JavascriptExecutor)driver).executeScript("document.body.style.transform='scale(0.9)'");
Its working for specific command lets say in my Listeners file i have place this if its a get command. it resize the browser after get URL and then it restored back to default once another command getting executed.
I'm looking for the solution like DesiredCapabilities of things so there i can add the zoom level for the browser.
FirefoxProfile profile= new FirefoxProfile();
profile.setPreference( "layout.css.devPixelsPerPx", "0.9" );
WebDriver driver = new FirefoxDriver(profile);
The above will set the firefox profile preference and simulate a zoom level of 90% for 110% set it to 1.1
How about something like this one -
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class A {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
Dimension dMax = driver.manage().window().getSize();
int mHeight = (int) (dMax.height *.9);
int mWidth = (int)(dMax.width *.9);
Dimension d = new Dimension(mWidth, mHeight);
driver.manage().window().setSize(d);
System.out.println( driver.manage().window().getSize());
}
}
There is not the capability level option is available in Firefox.
But screen size can be increased or decrease by webdriver:
driver.manage().window().setSize(value);

Unable to create or switch to new tab in Selenium Webdriver with JAVA on MAC

I've tried a different options just to open new tab but all of them lead to the same result : sending char "t" to google search field.
The goal in my real test is to switch between tabs in browser, but I am unable even open new one.
Very simple test
public class LoginPhp2 {
#Test
public void testGoogle() {
WebDriver driver = new SafariDriver();
driver.get("https://www.google.com");
//driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "t");
Actions action= new Actions(driver);
action.keyDown(Keys.COMMAND).sendKeys("t").build().perform();
//action.keyDown(Keys.COMMAND).sendKeys("t").keyUp(Keys.COMMAND).build().perform();
}
}
You may use javascript to open a new tab.
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open();");
There are different ways of opening new tabs in windows and Mac. Actual keys to send depend on your OS, for example, Mac uses COMMAND + t, instead of CONTROL + t.
You can open new tab in Mac using:
driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND +"t");
After this you can switch to any of the opened tabs:
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(0));
I have followed the approach suggested earlier:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open();");
This is opening new tab in the same window. I have tried it on my MAC machine

Selenium Internet Explorer click button

I have a problem. I want to click for button and open link in new tab. This my code:
Actions actions = new Actions(this.driver);
actions.keyDown(Keys.CONTROL).click(myButton).keyUp(Keys.CONTROL).perform();
But link is opened on current tab, not new tab.
This is bug of that?
P.S. on chrome and firefox this code work very well
One solution would be to open a new window before clicking the link :
WebDriver driver = new FirefoxDriver();
driver.get("http://stackoverflow.com");
// open a new window
((JavascriptExecutor)driver).executeScript("window.open(window.location.href, '_blank');");
// set the context to the new window
driver.switchTo().window(driver.getWindowHandles().toArray()[1]);
// click the link
driver.findElement(By.linkText("Stack Overflow")).click();
Another solution would be to set the target attribute on the targeted element:
WebDriver driver = new FirefoxDriver();
driver.get("http://stackoverflow.com");
WebElement element = driver.findElement(By.linkText("Stack Overflow"));
// set the target _blank on the link
((JavascriptExecutor)driver).executeScript("arguments[0].target='_blank';", element);
// click the link
element.click();
// set the context to the new window
driver.switchTo().window(driver.getWindowHandles().toArray()[1]);
Your code is fine but the IEDriver is not quite as good as the ones for FireFox and Chrome. I had similar issues, as you can read here. I ended up solving my issues with the java.awt.Robot. In your case that would mean you'd need an IE-specific method for opening in new tab.
Robot r = null;
try {
r = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
...
r.setAutoDelay(30);
r.keyPress(KeyEvent.VK_CONTROL);
//then click the button
r.keyRelease(KeyEvent.VK_CONTROL);
It's not elegant but it works.

Unable to execute Sikuli script after i click on the Web-element. ( Selenium webdriver with Java)

Here is my code
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
//Open the URL
driver.get("http://www.toolsqa.com/automation-practice-form/");
//Maximize the window
driver.manage().window().maximize();
//Click on Button which will open file upload window
driver.findElement(By.xpath(".//*[#id='photo']")).click();
// Implementing Sikuli
ScreenRegion s = new DesktopScreenRegion();
Target target = new ImageTarget(new File("D://SELENIUM WORK-PLACE/File_upload//img//Capture.PNG"));
ScreenRegion r = s.wait(target, 20000);
r=s.find(target); // Locate the target on the screen.
//Create a Canvas object of the type DesktopCanvas.
Canvas test = new DesktopCanvas();
test.addBox(r);
test.addLabel(r, "I am present here");
test.display(5);
}
}
Actual Result : Clicks on the Web-element, It opens a File upload box. Nothing happens. ( But if i close the Box and re-open it manually then it works fine)
Expected Output- It should work at the first time we open the File upload box.
Your code is fine. Fix the path to: "D://SELENIUM WORK-PLACE//File_upload//img//Capture.PNG"
Then, try using the below image for getting the Filename textfield instead. Because bigger the size of image, there are more possibilities of Sikuli being unable to detect the element as even a pixel's change might get in the way of Sikuli identifying an element.:

Selenium takes lots of time to get dynamic page of given URL

I am doing a Project in Java.
In this project I have to work with DOM.
For that I first load a dynamic page of any given URL, by using Selenium.
Then I parse them using Jsoup.
I want to get the dynamic page source code of given URL
Code snapshot:
public static void main(String[] args) throws IOException {
// Selenium
WebDriver driver = new FirefoxDriver();
driver.get("ANY URL HERE");
String html_content = driver.getPageSource();
driver.close();
// Jsoup makes DOM here by parsing HTML content
Document doc = Jsoup.parse(html_content);
// OPERATIONS USING DOM TREE
}
But the problem is, Selenium takes around 95% of the whole processing time, that is undesirable.
Selenium first opens Firefox, then loads the given page, then gets the dynamic page source code.
Can you tell me how I can reduce the time taken by Selenium, by replacing this tool with another efficient tool. Any other advice would also be welcome.
Edit NO. 1
There is some code given on this link.
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override", "some UA string");
WebDriver driver = new FirefoxDriver(profile);
But what is second line here, I didn't understand. As Documentation is also very poor of selenium.
Edit No. 2
System.out.println("Fetching %s..." + url1);
System.out.println("Fetching %s..." + url2);
WebDriver driver = new FirefoxDriver(createFirefoxProfile());
driver.get("url1");
String hml1 = driver.getPageSource();
driver.get("url2");
String hml2 = driver.getPageSource();
driver.close();
Document doc1 = Jsoup.parse(hml1);
Document doc2 = Jsoup.parse(hml2);
Try this:
public static void main(String[] args) throws IOException {
// Selenium
WebDriver driver = new FirefoxDriver(createFirefoxProfile());
driver.get("ANY URL HERE");
String html_content = driver.getPageSource();
driver.close();
// Jsoup makes DOM here by parsing HTML content
// OPERATIONS USING DOM TREE
}
private static FirefoxProfile createFirefoxProfile() {
File profileDir = new File("/tmp/firefox-profile-dir");
if (profileDir.exists())
return new FirefoxProfile(profileDir);
FirefoxProfile firefoxProfile = new FirefoxProfile();
File dir = firefoxProfile.layoutOnDisk();
try {
profileDir.mkdirs();
FileUtils.copyDirectory(dir, profileDir);
} catch (IOException e) {
e.printStackTrace();
}
return firefoxProfile;
}
The createFireFoxProfile() method creates a profile if one doesn't exist. It uses if a profile already exists. So selenium doesn't need to create the profile-dir structure each and every time.
if you are sure, confident about your code, you can go with phantomjs. it is a headless browser and will get your results with quick hits. FF will take time to execute.

Categories

Resources