TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Selenium Webdriver Coding Tips for 2024
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Automation TricksSelenium Tutorial

Selenium Webdriver Coding Tips for 2024

Last updated: Mar 03, 2024 12:34 pm
By Meenakshi Agarwal
Share
12 Min Read
Selenium Webdriver Coding Tips to Improve Quality
Selenium Webdriver Coding Tips.
SHARE

Selenium Webdriver is a powerful automation tool for testing web applications. It’s an open-source library bundled with a rich set of features. Using it for testing a website is just like simulating the actions of a real user. All these abilities together make it a perfect tool for automation. But you need proper guidance to get the best out of it. In this blog post, we’ve assembled some of the best Selenium Webdriver coding tips for software testers.

Contents
Tip-1: Best method to create a Webdriver instance.Tip-2: Simple method to check if an element exists.Tip-3: Avoid Exception while checking an element exists.Tip-4: Wait for a page with JavaScript(JS) to load.Tip-5: Take a screenshot using Webdriver.Tip-6: Take a partial screenshot using Selenium Webdriver.Tip-7: Get the HTML Source of WebElement in Selenium WebDriver.Tip-8: How to select/get the drop-down option in Selenium Webdriver.Tip-9: Refreshing web page by WebDriver during tests.Tip-10: Run A JavaScript Code Using Selenium Webdriver.Tip-11: Getting the result of Javascript code in Webdriver.Tip-12: Perform the mouseover function using WebDriver in Java.Tip-13: Make Selenium WebDriver click a checkbox that is not currently visible.Tip-14: Switch to a new browser window in Webdriver.Tip-15: Setting the driver executable path in Webdriver.Tip-16: Find the element using CSS in Webdriver.Tip-17: Open a new tab using Selenium WebDriver in Java.Tip-18: Handle Ajax calls in Selenium Webdriver.Tip-19: Scheduling Selenium Webdriver tests in Windows 7.Tip-20: Scheduling Selenium Webdriver tests in Linux.

With these tips, you’ll be able to optimize code, improve quality, and provide robust automation solutions. Selenium Webdriver supports a lot of programming languages such as Java, Python, C#, and Ruby. But in this article, we’ll focus only on Java-based tips for Selenium. Though, you can easily change them to the language of your choice.

To download the latest Selenium automation tool, please Download Selenium Webdriver. And follow the step-by-step Selenium Webdriver tutorial to create a quick Selenium demo from scratch.

20 Selenium Webdriver Coding Tips

With these Selenium Webdriver coding tips, we’ve tried to cover various use cases that you face in real time. We expect you to use these coding snippets directly in your current project assignments. BTW if you fall into any issues while using these tips, then do write to us. We’ll try to respond to every query of our readers.

Selenium Webdriver Coding Tips to Improve Quality
Selenium Webdriver Coding Tips.

Tip-1: Best method to create a Webdriver instance.

It’s one of the most common Selenium Webdriver coding tips that you can’t avoid using.

1.1- Use the <Factory> design pattern to create objects based on browser type.

1.2- Extend the below code or use it as is in your projects.

public class DriverFactory {
    private WebDriver driver = null;

    public static WebDriver getBrowser(String browserType) {
        if (driver == null) {
            if (browserType.equals("Firefox"))

            {
                driver = new FirefoxDriver();

            } else if (browserType.equals("Chrome"))

            {
                driver = new ChromeDriver();

            } else if (browserType.equals("IE"))

            {
                driver = new InternetExplorerDriver();

            }
        }
        return driver;
    }
}

Tip-2: Simple method to check if an element exists.

2.1- You should use <findElements> instead of <findElement>.

2.2- <findElements> returns an empty list when it doesn’t find any matching elements.

2.3- You can use the code given below to check for the presence of an element.

Boolean isItemPresent = driver.findElements(By.testLocator).size() > 0

Tip-3: Avoid Exception while checking an element exists.

3.1- The code in the previous tip may lead to <NoSuchElementException>. Also, it could be a bit slower in some cases.

3.2- Webdriver has a Fluent wait feature. We can use it to check the element.

3.3- It gives the ability to ignore any exception and allows to testing of the <WebElement>. Let’s see how to achieve what’s said here.

/* 1- Test if an element exists on the page.
   2- Ignore the no element found exception.
 */
By element = By.xpath(".//*[@id='demo']/p");
Wait < WebDriver > wait = new FluentWait < > (driver)
    .withTimeout(60, TimeUnit.SECONDS)
    .pollingEvery(5, TimeUnit.SECONDS)
    .ignoring(NoSuchElementException.class);
wait.until(ExpectedConditions
    .presenceOfElementLocated(element));

Tip-4: Wait for a page with JavaScript(JS) to load.

4.1- It’s quite common to work with pages bloated with JavaScript. The challenge is how to make sure the page has finished loading.

4.2- Here, we are giving a solution that works. This code will help you set to wait for a page containing JavaScript.

wait.until(new Predicate < WebDriver > () {
    @Override
    public Boolean apply(WebDriver driver) {
        return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
    }
});

Tip-5: Take a screenshot using Webdriver.

5.1- It’s easy to capture a screenshot of any error using Webdriver.

5.2- Use the below Webdriver code. It saves the screenshot to the current project directory.

WebDriver driver = new FirefoxDriver();
driver.get("https://techBeamers.com/");

// Store the screenshot in current project dir.
String screenShot = System.getProperty("user.dir") + "\\screenShot.png";

// Call Webdriver to click the screenshot.
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

// Save the screenshot.
FileUtils.copyFile(scrFile, new File(screenShot));

Tip-6: Take a partial screenshot using Selenium Webdriver.

It’s one of the premium Selenium Webdriver coding tips.

6.1- Sometimes you only need to take a screenshot of the part of the screen. Like only one frame within a set of frames.

6.2- You can add the below code in your project to shoot the image of a particular frame.

6.3- Find the <WebElement> of the frame and pass it to the function given below.

public void takePartialScreenShot(WebElement element) throws IOException {

    String screenShot = System.getProperty("user.dir") + "\\screenShot.png";

    File screen = ((TakesScreenshot) this.driver).getScreenshotAs(OutputType.FILE);

    Point p = element.getLocation();

    int width = element.getSize().getWidth();
    int height = element.getSize().getHeight();

    BufferedImage img = ImageIO.read(screen);

    BufferedImage dest = img.getSubimage(p.getX(), p.getY(), width,
        height);

    ImageIO.write(dest, "png", screen);

    FileUtils.copyFile(screen, new File(screenShot));
}

6.4- You may require adding a few imports to get the above code working.

import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

6.5- Alternatively, you can use the <CTRL+SHIFT+O> shortcut in Eclipse.

Tip-7: Get the HTML Source of WebElement in Selenium WebDriver.

7.1- Webdriver’s <WebElement> class provides <getAttribute()> method to get the HTML inside the element.

7.2- You need to pass the <innerHTML> as an attribute type in the above method. See the code below.

String html = element.getAttribute("innerHTML");

Tip-8: How to select/get the drop-down option in Selenium Webdriver.

You can achieve this in the following two steps.

8.1- Select an option based on the label.

Select dropdown = new Select(driver.findElement(By.xpath("//drop_down_x_path")));
dropdown.deselectAll();
dropdown.selectByVisibleText("selectLabel");

8.2- Get the first selected value from the drop-down.

WebElement option = dropdown.getFirstSelectedOption();

Tip-9: Refreshing web page by WebDriver during tests.

9.1- The below code should refresh the web page.

driver.navigate().refresh();

Tip-10: Run A JavaScript Code Using Selenium Webdriver.

10.1- When you are testing a website, you can’t skip using JavaScript.

10.2- Webdriver provides support to call JavaScript.

10.3- You just need to add the below lines to your project.

JavascriptExecutor JS = (JavascriptExecutor) driver;
JS.executeScript("alert('hello world')");

Tip-11: Getting the result of Javascript code in Webdriver.

11.1- It’s a bit tricky but easy. Use the <return> keyword in JavaScript to send back the result.

11.2- Place the following code in your project.

((JavascriptExecutor) driver).executeScript("return 10");

Tip-12: Perform the mouseover function using WebDriver in Java.

12.1- Sometimes you need to use a mouseover function with a drop-down menu.

12.3- When you hover over the menu, it shows new options.

12.5- Webdriver provides a <Actions> class to handle mouse events.

12.4- We can achieve this by chaining all actions to simulate mouse hover.

Actions action = new Actions(driver);
WebElement item = driver.findElement(By.xpath("html/body/div[5]/ul/li[5]/a"));
action.moveToElement(item).moveToElement(driver.findElement(By.xpath("/write-expression-here"))).click().build().perform();

Tip-13: Make Selenium WebDriver click a checkbox that is not currently visible.

13.1- Sometimes you’ve to click checkboxes on a form. But you fall into problems when they get added dynamically.

13.2- If you use Webdriver calls, then the following error occurs.

"Element is not currently visible and so may not be interacted with."

13.3- In such cases, we advise using Webdriver’s JavaScript executor to do the job.

13.4- Check out the below lines of code.

((JavascriptExecutor)driver).executeScript("arguments[0].checked = true;", checkbox);

Tip-14: Switch to a new browser window in Webdriver.

14.1- You can easily switch between popup windows.

14.2- Copy the below code in your project to switch windows.

// Get the current window handle.
String hBefore = driver.getWindowHandle();

// Click to open new windows.

// Switch to new windows.
for(String hNew: driver.getWindowHandles()){
    driver.switchTo().window(hNew);
}

// Close all new windows.
driver.close();

// Switch back to first window.
driver.switchTo().window(hBefore);

// Resume your work.

Tip-15: Setting the driver executable path in Webdriver.

15.1- For some browsers, Webdriver needs to know the locations of their driver files. e.g. Chrome, and IE.

15.2- We need to set the driver file path in the Webdriver configuration.

15.3- See the code snippet given below. We took IE as an example.

File ieDriver = new File("path/to/iexploredriver.exe");
System.setProperty("webdriver.ie.driver", ieDriver.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();

Tip-16: Find the element using CSS in Webdriver.

16.1- While working with list items, you may find it interesting to use CSS for locating elements. Let’s learn in-depth with the help of examples.

16.2- Use case: You’ve to find the third element from a list. The element is an anchor text and uses <css1> and <css2> classes for styling.

16.3- Implement with <By.CssSelector>.

IList<IWebElement> list = driver.FindElements(By.CssSelector(".css1.css2"));
IWebElement target = list[3];

16.4- Implement with <By.XPath>.

driver.FindElement(By.XPath("(//a[contains(@class, 'css1 css2')])[3]"));

Tip-17: Open a new tab using Selenium WebDriver in Java.

17.1- At times you may need to open a new tab in the same browser window. It’s easy to do it, use the following code.

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

17.2- If you wish to run your tests in the new tab, then you’ve to switch to it first. Check out the given code fragment.

ArrayList<String> tablist = new ArrayList<String> (driver.getWindowHandles());

driver.switchTo().window(tablist.get(0));

 Now let’s hear some of the premium Selenium Webdriver coding tips that we’ve already published on our blog.

Tip-18: Handle Ajax calls in Selenium Webdriver.

18.1- Read the below post to see 6 unique ways to handle Ajax calls.

6 Ways to Handle Ajax Calls

Tip-19: Scheduling Selenium Webdriver tests in Windows 7.

19.1- Read the below post to set up Selenium Webdriver testing using the Windows task scheduler.

Selenium Webdriver in Windows 7

Tip-20: Scheduling Selenium Webdriver tests in Linux.

20.1- Read the below post to run Selenium Webdriver tests using crontab in Linux.

Selenium Webdriver in Linux

Footnote – Selenium Webdriver Coding Tips

We wish the above post would have been able to hit the right chord with you. We’ve tried hard to touch upon all basic, advanced, and premium Selenium Webdriver coding tips.

We believe these quickies would not only solve your problems but also help in upgrading your Selenium Webdriver coding skills. Our end goal is to see you outshining in your work. That’s why we keep researching new ways to use and innovate using Selenium Webdriver, Java, and Python.

So, help us reach this post further to benefit every other individual who’s striving to learn automation. Don’t just leave without a like, share, or comment. 🙂

Best,

TechBeamers.

You Might Also Like

20 Demo Sites for Automation Testing

Page Object Model (POM) and Page Factory Guide in Selenium Java

Selenium 4 Relative Locators Guide

Selenium Version 4 Features – What’s New?

How to Inspect Element in Safari, Android, and iPhone

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Run Selenium Tests Using Crontab in Ubuntu 14.04 Run Selenium Tests Using Crontab in Ubuntu
Next Article Why Should You Run Selenium Tests in Cloud How to Run Selenium Tests in the Cloud

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x