After my previous post on Selenium 4 Relative Locators, I further explored Selenium4 features and found a few more goodies in WebElement and WebDriver interfaces.
Yes, now we can capture screenshot of an individual element or group of elements. This is a very useful feature. I talked about capturing element screenshots in my Selenium Testing Tools Cookbook. However, the new feature added in Selenium 4 (alpha-3) is inbuilt and much simpler.
The WebElement interface now supports getScreenShotAs() method by implementing the TakesScreenshot to capture a screenshot of the element.
This method accepts the OutputType argument and screenshots can be captured as FILE, BYTES or BASE64 string.
Let’s try to capture screenshot of a link and the search box displayed on Google Search Home page:
// find the Images link on Google Search home page WebElement imagesLink = driver.findElement(By.linkText("Images")); // take a screenshot of the link element File linkScr = imagesLink.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(linkScr, new File("./target/linkScr.png"));
We can also capture a group of elements by taking a screenshot of the parent element. Here is a complete example capturing the Images link and the search box:
The new getRect() method
The new getRect() method is introduced in WebDriver interface which is essentially a combination of previous getSize() and getLocation() methods. Here’s a difference between previous methods and new the getRect() method which returns a Rectangle object:
New additions in WebDriver
In addition, to maximize() method, the browser window can now be made fullscreen by using the new fullscreen() method:
A new parentFrame() method is added for navigating between frames.
I’m not really sure if this is completely new feature (or maybe I’m too lazy to go through the changes) but we can now create a new empty tab or new browser window by using the newWindow() method.
That’s it for now. I’ll deep dive into new Selenium Grid features in an upcoming post.
These features are in alpha release and subject to change in future. Please use with caution. You can find the complete code example from this post in my GitHub repo https://github.com/upgundecha/selenium4