Skip to content

Software Development at Program Tom LTD

Place for coding, programming, development and software in general.

Menu
  • Blog
  • PDF Booklets
  • Dev Utils & Content
  • Java Spring Boot Or Web Apps
  • English
    • български
    • English
    • Español
    • Português
    • हिन्दी
    • Русский
    • Deutsch
    • Français
    • Italiano
    • العربية
  • About Us
  • Cart
Menu
Browser Automation with Selenium and Java

Browser Automation with Selenium and Java

Posted on May 22, 2025 by Toma Velev

To automate entering data in a browser where inputs vary (like incrementing integers), you can use a Browser Automation like Selenium and I prefer implementing it in Java.


🥇 Best Overall (Flexible and Powerful): Playwright or Selenium

  • Languages: Python, JavaScript, Java, C#
  • Best for: Full browser automation, dynamic form filling, handling modern websites (SPAs, React, etc.)
  • Can do:
    • Launch a browser, navigate to a page
    • Locate fields by ID/name/xpath
    • Fill in variable values (e.g. loop with integers)
    • Submit forms, wait for responses

Example (Python + Playwright):

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto("https://example.com/form")

    for i in range(10):
        page.fill("#input1", f"User-{i}")
        page.fill("#input2", str(100 + i))
        page.click("#submit-button")
        page.wait_for_timeout(1000)  # wait 1s between entries

    browser.close()

✅ Simpler Option (No Code): UI.Vision RPA (Browser Extension)

  • Best for: Simple repetitive form filling in Chrome or Firefox
  • Pros: Easy to install, record and play macros, use CSV to loop data
  • Cons: Less control than code-based tools

✨ BONUS: Headless Mode & Data-Driven Testing

You can combine these tools with:

  • CSV, Excel, or databases to drive input
  • Conditional logic for different field values
  • Screenshots and logging

Selenium

 

✅ What Selenium Can Do for Your Use Case

  • Open a browser (Chrome, Firefox, etc.)
  • Navigate to a webpage
  • Locate input fields using id, name, xpath, etc.
  • Input data (e.g., loop from 1 to N and enter in each iteration)
  • Click buttons or submit forms
  • Wait for elements or delays as needed

🛠 Useful Features

  • Wait for elements: Use WebDriverWait for dynamic pages
  • Data from CSV: Load values from a file to loop through
  • Headless mode: Run without opening a visible browser window (for automation on servers)

Here’s a Java + Selenium example that automates filling out a form with incrementing integer data. This version:

  • Uses ChromeDriver
  • Fills two input fields (name and age)
  • Clicks a submit button
  • Loops 10 times, each time incrementing the data
  • Waits a bit between iterations

✅ Prerequisites

  1. Add Selenium to your project:
    • If you’re using Maven, add this to your pom.xml:
      <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.19.1</version>
      </dependency>
      
  2. Download and place ChromeDriver in your system PATH. Make sure the version matches your Chrome browser.

🧩 Java Code (Selenium + Chrome)

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FormAutomation {
    public static void main(String[] args) {
        // Launch ChromeDriver
        WebDriver driver = new ChromeDriver();

        try {
            for (int i = 0; i < 10; i++) {
                // Navigate to form page
                driver.get("https://example.com/form");

                // Locate and fill the "name" input
                WebElement nameInput = driver.findElement(By.id("name-field"));
                nameInput.clear();
                nameInput.sendKeys("User-" + i);

                // Locate and fill the "age" input
                WebElement ageInput = driver.findElement(By.id("age-field"));
                ageInput.clear();
                ageInput.sendKeys(String.valueOf(20 + i));

                // Click the submit button
                WebElement submitBtn = driver.findElement(By.id("submit-button"));
                submitBtn.click();

                // Wait 1 second before next iteration
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            driver.quit();
        }
    }
}

🛠 Customizing

  • Replace "https://example.com/form" with your actual URL.
  • Update "name-field", "age-field", and "submit-button" to match the HTML element IDs of your form. You can also use By.name(), By.className(), or By.xpath() if needed.

✅ Command to Initialize a Maven Project

mvn archetype:generate -DgroupId=com.example.selenium \
  -DartifactId=form-automation \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DinteractiveMode=false

This creates a project with:

  • Group ID: com.example.selenium
  • Artifact ID (project folder): form-automation
  • Java starter structure (src/main/java, src/test/java)

📦 After Initialization: Add Selenium Dependency

Open the generated form-automation/pom.xml and add this inside <dependencies>:

<dependencies>
  <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.19.1</version>
  </dependency>
</dependencies>

▶️ Compile and Run

  1. Go into the project directory:
    cd form-automation
    
  2. Compile the project:
    mvn compile
    
  3. Run the main class (replace App with your actual class name):
    mvn exec:java -Dexec.mainClass="com.example.selenium.App"
    

    If exec-maven-plugin is not yet added, insert this into your pom.xml:

    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <version>3.1.0</version>
          <executions>
            <execution>
              <goals>
                <goal>java</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </build>
    

 

✅ Java Example with XPath

WebElement newButton = driver.findElement(By.xpath("//button[text()='New']"));

This matches:

<button>New</button>

🧠 Variants & Tips

1. Text Contains “New” (e.g. <button>New Item</button>)

WebElement newButton = driver.findElement(By.xpath("//button[contains(text(), 'New')]"));

2. Case-insensitive (not directly supported in XPath 1.0, but workaround exists):

WebElement newButton = driver.findElement(By.xpath(
  "//button[translate(text(), 'NEW', 'new') = 'new']"
));

3. Using CSS Selector + Text (Not supported directly by CSS, but possible with JS or XPath):

// Not possible directly via CSS to query by text, use XPath instead

4. Generic clickable with text “New” (e.g. ,

, etc.):
WebElement newButton = driver.findElement(By.xpath("//*[text()='New']"));

How to have css selector by attribute name and value

To select an element by **attribute name and value** using a **CSS selector**, you use this syntax:

[attributeName='value']

✅ Examples:

1. Select a button with a custom attribute:

WebElement button = driver.findElement(By.cssSelector("button[data-action='new']"));
``&gt;
Matches:
```html
<button data-action="new">New</button>

2. Select an input with name=”email”:

WebElement input = driver.findElement(By.cssSelector("input[name='email']"));

3. Select a div with class btn and attribute role="button":

WebElement divBtn = driver.findElement(By.cssSelector("div.btn[role='button']"));

🧠 Attribute Matching Variants in CSS Selectors

| Selector | Matches |
| —————- | ————————- |
| [attr='value'] | Exact match |
| [attr^='val'] | Starts with "val" |
| [attr$='val'] | Ends with "val" |
| [attr*='val'] | Contains "val" anywhere |

Example:

// input whose name starts with "user"
driver.findElement(By.cssSelector("input[name^='user']"));

Special Keys

In Selenium (Java), you can simulate keyboard key presses like Enter, Arrow Left, or Arrow Right using the sendKeys() method along with the Keys enum from org.openqa.selenium.Keys.


✅ Example: Pressing Enter, Arrow Left, Arrow Right

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.Keys;

public class KeyPressExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");

        WebElement input = driver.findElement(By.id("some-input"));

        // Focus the element
        input.click();

        // Type something
        input.sendKeys("Hello");

        // Simulate arrow left to move cursor
        input.sendKeys(Keys.ARROW_LEFT);

        // Simulate pressing Enter
        input.sendKeys(Keys.ENTER);

        // Optional: wait a bit before closing
        try { Thread.sleep(1000); } catch (InterruptedException e) {}
        driver.quit();
    }
}

🧠 Common Keys

Key Usage
Keys.ENTER Submit or trigger action
Keys.RETURN Same as ENTER
Keys.ARROW_LEFT Move cursor left
Keys.ARROW_RIGHT Move cursor right
Keys.TAB Move to next input field
Keys.ESCAPE Cancel/close modals

🧪 Tip for Chaining Keys

You can also combine keys:

input.sendKeys(Keys.chord(Keys.CONTROL, "a")); // Ctrl+A to select all

Let me know what interaction you want exactly (e.g. navigating a dropdown, editing text input), and I’ll tailor the key sequence.

How to have File Picker

To interact with a file picker (file upload input) using Selenium, you don’t need to deal with the native file dialog — instead, you send the full file path directly to the <input type="file"> element.


✅ Java Example: Upload a File

Assume the HTML looks like this:

<input type="file" id="fileUpload">

Here’s the Selenium Java code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FileUploadExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com/upload");

        // Locate the file input element
        WebElement fileInput = driver.findElement(By.id("fileUpload"));

        // Provide the full path to the file you want to upload
        String filePath = "/absolute/path/to/your/file.txt";
        fileInput.sendKeys(filePath);

        // Optionally submit the form or click the upload button
        driver.findElement(By.id("submitBtn")).click();

        driver.quit();
    }
}

⚠️ Important Notes

  • Do not use click() to open the native file picker — it’s not supported for automation.
  • The file input must not be hidden (display: none) — if it is, you’ll need to:
    • Remove the style via JavaScript:
      ((JavascriptExecutor) driver).executeScript("arguments[0].style.display = 'block';", fileInput);
      

What does .ElementClickInterceptedException: element click intercepted: mean

The ElementClickInterceptedException in Selenium means that when you tried to click on a given element, that click never actually reached it because something else was “on top” of it (intercepting the click). In other words, Selenium tried to click at the element’s coordinates, but a different element—an overlay, modal dialog, spinner, sticky header, etc.—was covering it in the browser viewport, so the click went to the covering element instead.


🛑 Common Causes

  1. Loading spinners or overlays
    A progress overlay (e.g. a “loading…” screen) is still visible.
  2. Modal dialogs, pop‑ups, or tooltips
    An alert/modal that hasn’t been dismissed is floating above your target.
  3. Fixed headers or footers
    A sticky navbar or footer bar is covering part of the page.
  4. Animations or transitions
    A CSS animation is moving elements around, so at click time the target isn’t stationary.

📦 Example Exception

org.openqa.selenium.ElementClickInterceptedException:
 element click intercepted:
 Element <button id="submit">...</button>
 is not clickable at point (x, y). Other element would receive the click: <div class="modal-backdrop">...</div>

🛠 How to Fix

  1. Wait for blockers to disappear
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    // wait until overlay is gone
    wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".modal-backdrop")));
    // now click
    driver.findElement(By.id("submit")).click();
    
  2. Scroll the element into view
    WebElement btn = driver.findElement(By.id("submit"));
    ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", btn);
    btn.click();
    
  3. Wait until the element is clickable
    WebElement clickable = wait.until(
        ExpectedConditions.elementToBeClickable(By.id("submit"))
    );
    clickable.click();
    
  4. Use JavaScript click as a last resort
    WebElement btn = driver.findElement(By.id("submit"));
    ((JavascriptExecutor) driver).executeScript("arguments[0].click();", btn);
    
  5. Dismiss interfering pop‑ups
    If a modal or tooltip is open, close it first:

    driver.findElement(By.cssSelector(".modal-close")).click();
    wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".modal")));
    driver.findElement(By.id("submit")).click();
    

🔍 Debugging Tips

  • Take a screenshot right before the click to see what’s on top.
  • Print the page source or inspect the DOM to find overlays.
  • Check CSS z‑index values: the intercepting element likely has a higher z-index.

By ensuring your target is truly “clickable” and not covered by anything else, you’ll avoid ElementClickInterceptedException.

  • Prompt-to-Production: How AI is Forcing Us to Build Higher Quality Software
  • Debug Web View Flutter App
  • Skipping AI? You’re a Relic – Time to Evolve or Perish!
  • 2026 Flutter Launch Blueprint: Your 10-Step Checklist to App Store Domination
  • Product Requirements Document – for different software development levels

Categories

  • Apps (25)
  • ChatGPT (27)
  • Choosing a Framework (38)
  • Flutter (281)
  • Graphical User Interface (14)
  • Marketing (119)
  • Software Development (292)
  • Spring (45)
  • StartUp (22)
  • Uncategorized (14)
  • Uncategorized (4)
  • Vaadin (16)

Tags

Algorithms (9) crypto (29) flutterdev (39) General (86) Java (7) QR & Bar Codes (3) Software Dev Choices (33) Spring Boot (1) standards (1) Theme (3) User Authentication & Authorization (9) User Experience (10) Utilities (19) WordPress (11)

Product categories

  • All Technologies (87)
    • Flutter Apps (26)
    • GPT (4)
    • Java (39)
    • Native Android (3)
    • PHP (9)
    • Spring (Boot) / Quarkus (36)
    • Utils (15)
    • Vaadin 24+ (28)
    • Vaadin 8 (1)
  • Apps (18)
    • Employees DB (1)
    • Notes (6)
    • Personal Budget (1)
    • Recipes Book (1)
    • Stuff Organizer (1)
    • To-Do (2)
  • PDF Books (3)
  • Source Code Generators (8)

Recent Posts

  • Prompt-to-Production: How AI is Forcing Us to Build Higher Quality Software
  • Debug Web View Flutter App
  • Skipping AI? You’re a Relic – Time to Evolve or Perish!
  • 2026 Flutter Launch Blueprint: Your 10-Step Checklist to App Store Domination
  • Product Requirements Document – for different software development levels

Post Categories

  • Apps (25)
  • ChatGPT (27)
  • Choosing a Framework (38)
  • Flutter (281)
  • Graphical User Interface (14)
  • Marketing (119)
  • Software Development (292)
  • Spring (45)
  • StartUp (22)
  • Uncategorized (14)
  • Uncategorized (4)
  • Vaadin (16)