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 Howtos (10) 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 Howtos (10) for 2024

Last updated: Feb 25, 2024 12:42 pm
By Meenakshi Agarwal
Share
8 Min Read
10 Most Common Selenium Webdriver Howtos
10 Selenium Webdriver Howtos.
SHARE

This tutorial discusses the ten essential Selenium Webdriver howtos that address many of real-time issues with Selenium automation.

Contents
1. How to use Selenium Webdriver to click Google search?2. What to do when the click doesn’t work in Selenium Webdriver?3. Provide code to simulate mouseover in Selenium Webdriver.4. How to open a URL in the new tab with Selenium WebDriver?5. Selenium Webdriver code to extract data from the PDF files.6. How to get elements by XPath using JavaScript in Selenium WebDriver?7. How to select the drop-down option in Selenium Webdriver?8. Code to select all the drop-down values using Selenium WebDriver.9. Code to get all the children of an element using Webdriver.10. Provide code to get the visible text of a page.

With every how-to, there is a piece of code given to demonstrate the usage. You can use the sample code right away in your projects.

Before you dive in further, we must tell you that the tips here will only provide a partial solution that you can reuse in your programs. So we assume you know the basics of Selenium Webdriver.

Must read – 100+ Selenium interview questions to ramp up preparation

Let’s now open up this post with a solution to one of the most common use cases – how to automate web tables in a web application.

It is about handling the web tables where we will show how to query a table to fetch data from its cells.

//Create the Firefox driver instance.
WebDriver ff = new FirefoxDriver();

//First, find the table on the web page.
WebElement table = ff.findElement(By.id(searchResultsGrid));

//Second, fetch all the row elements of the table.
List<WebElement> rowSet = table.findElements(By.tagName("tr"));

//Third, loop through the rows and get the data from their cells.
for (WebElement row : rowSet) {
 List<WebElement> cells = row.findElements(By.xpath("./*"));
 for (WebElement cell : cells) {
 //Continue checking.
 }
}

The above code was just a demo before we shared the rest of the useful Selenium tips. Please go through the below list to see the other pieces of Selenium Webdriver howtos.

1. How to use Selenium Webdriver to click Google search?

Since Google optimizes its CSS and JS scripts, you can’t purely rely on using them as locators. Moreover, it adds the search links dynamically on the result page. So you have to use a smart wait for the page to show all the results.

/*
 # Selenium Webdriver to click Google search and wait for the results.
 # ===================================================================
 */
public static void main(String[] args) {

    WebDriver ff = new FirefoxDriver();
    ff.get("http://www.google.com");
    WebElement search = ff.findElement(By.name("q"));
    search.sendKeys("Hello world!\n");
    search.submit();

    // Wait until Google finishes displaying the results.
    WebElement waitForResult = (new WebDriverWait(ff, 10))
              .until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));

    List<WebElement> searches = ff.findElements(By.xpath("//*[@id='rso']//h3/a"));

    // Print all the links appeared in the search.
    for (WebElement lnk : searches)
    {
        System.out.println(lnk.getAttribute("href"));
    }
}

2. What to do when the click doesn’t work in Selenium Webdriver?

First of all, you need to check that the element you are clicking is present on the target page. Then, you can try using the below code.

ff.findElement(By.name("submit")).sendKeys(Keys.Return);
or
ff.findElement(By.name("submit")).sendKeys(Keys.Enter);

3. Provide code to simulate mouseover in Selenium Webdriver.

Since it’s not realistic to achieve <mouse hover> in Selenium Webdriver, we can sequence all the actions in one go. It will give the same effect as mouseover would have.

Here is the three-line code you can use.

Actions action = new Actions(ff);
WebElement seq = ff.findElement(By.xpath("html/body/div[10]/ul/li[5]/a"));
action.moveToElement(seq).moveToElement(ff.findElement(By.xpath("/paste-expression"))).click().build().perform();

4. How to open a URL in the new tab with Selenium WebDriver?

Here is the Selenium Webdriver code snippet that will help in opening the new tab.

It’ll open the page in a new tab.

String newtab = Keys.chord(Keys.CONTROL,Keys.RETURN); 
ff.findElement(By.linkText("URL")).sendKeys(newtab);

If you wish to move to the new tab, then use the below code.

ArrayList<String> tablist = new ArrayList<String> (ff.getWindowHandles());
ff.switchTo().window(tablist.get(0));

These Selenium Webdriver Howtos are some of the worth experimenting with, check out a few more below.

5. Selenium Webdriver code to extract data from the PDF files.

Probably, you’ve heard many times that you need to check a page that loads the PDF.

Here is the code to verify the online PDF file. But you first need to download the Apache PDF library.

@Test
public void checkPDFpage() throws Exception {
    // Test page which loads pdf document.
    ff.get("http ... sample page loading pdf");
 
    URL nav = new URL(ff.getCurrentUrl());
    BufferedInputStream page = new BufferedInputStream(nav.openStream());
 
    PDDocument pdfdoc = null;
    try{
        pdfdoc = PDDocument.load(page);
        String result = new PDFTextStripper().getText(pdfdoc);
        System.out.println(result);
    }finally{
 
        if( pdfdoc != null )
        {
            pdfdoc.close();
        }//end of if
    }//finally
}//main

6. How to get elements by XPath using JavaScript in Selenium WebDriver?

Here is an easy way to retrieve the XPath using JS. Just use the JS <document.evaluate> method to fetch the XPath.

function getElementByXpath(path) {
  return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

Next, you may have to call the above JavaScript function from the Webdriver code. So use the <JavascriptExecutor> as given below.

WebDriver ff = new FirefoxDriver();
if (ff instanceof JavascriptExecutor) {
    ((JavascriptExecutor) ff).executeScript("getElementByXpath('//xpath')");
}

How is it going with our special list of Selenium Webdriver Howtos? We hope you are enjoying writing so much code.

7. How to select the drop-down option in Selenium Webdriver?

Use the following Webdriver code. It’ll help in selecting the options based on the label.

Select sel = new Select(ff.findElement(By.xpath("//path_to_drop_down")));
sel.deselectAll();
sel.selectByVisibleText("myvalue");

Also, you can add the below code to get the first selected value.

WebElement selection = sel.getFirstSelectedOption();

8. Code to select all the drop-down values using Selenium WebDriver.

Here is the code to select all values from the drop-down.

WebElement sel = ff.findElement(By.id("month"));
List<WebElement> items = sel.findElements(By.tagName("option"));

for (WebElement item : items) {
       item.click();
}

9. Code to get all the children of an element using Webdriver.

You can query all the children of an element in Selenium Webdriver by using both the XPath and the CSS.

List<WebElement> nodes = targetElement.findElements(By.xpath(".//*"));

Or

List<WebElement> nodes = targetElement.findElements(By.cssSelector("*"));

Finally, we approached the last mile and the last of the 10 Selenium Webdriver Howtos.

10. Provide code to get the visible text of a page.

You need to run through the following steps to get the visible text.

  • Call <By.tagName(“body”)> to select the top element in the DOM.
  • Next, use the <getText()> methods on the same element. It will return the desired visible text.

Also Read: Top 20 Selenium Webdriver Coding Tips for Beginners

Summary

You might have observed that merely reading Selenium Webdriver tutorials aren’t going to turn us into automation geek. There are a number of other technical things that matter and we should know as automation testers.

However, most of the tutorials fail to address such common problems. Hence, we did a trial, researched, and rinsed the ten problems that many automation testers encounter in their work. And finally, this post on ten Selenium Webdriver howtos came through.

If you have any questions about the Selenium Webdriver howtos, then please feel free to ask them. Also, if you want to share some of yours, then let us know. We’ll get them added to this post and mention your reference there.

Keep Learning,

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

TAGGED:Advanced Selenium TutorialWebdriver Interview
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 Python MongoDB Programming Tutorial for Beginners How to Connect MongoDB with Python
Next Article Python File Handling Tutorial and Examples for Beginners How to Use File I/O in Python Programs

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