Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. Java
  4. Can only iterate over an array or an instance of java.lang.Iterable

Can only iterate over an array or an instance of java.lang.Iterable

Date- Aug 31,2023 Updated Feb 2026 3843
java selenium

Overview of Selenium WebDriver

Selenium WebDriver is a popular open-source tool that allows developers to automate web applications for testing purposes. It provides a simple API for interacting with web browsers and can simulate user actions such as clicking buttons, entering text, and navigating between pages. One common task in web automation is the need to find and interact with multiple elements on a page, such as links represented by anchor tags (<a> elements).

In this tutorial, we will explore how to correctly retrieve and iterate over collections of WebElement objects, specifically focusing on anchor tags. Understanding this process can significantly enhance your automation scripts, allowing for more efficient and scalable tests.

Prerequisites

Before diving into the code examples, ensure you have the following prerequisites:

  • Java Development Kit (JDK): Make sure you have JDK installed on your machine.
  • Maven or Gradle: These are build tools that help manage dependencies. You can choose either based on your preference.
  • Selenium WebDriver: Include the Selenium WebDriver library in your project. If using Maven, add the following dependency:
<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.0.0</version>
</dependency>

Finding Elements with Selenium

To interact with multiple anchor tags on a webpage, you need to use the findElements method provided by the WebDriver API. This method returns a list of WebElement objects, allowing you to work with each element individually.

Here’s a corrected example of how to find and iterate over all anchor tags on a webpage:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;

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

        List<WebElement> anchorElements = driver.findElements(By.tagName("a"));

        for (WebElement anchor : anchorElements) {
            System.out.println(anchor.getText()); // Print the text of each anchor
        }

        driver.quit();
    }
}
Can only iterate over an array or an instance of javalangIterable

Iterating Over WebElements

The for-each loop provides a convenient way to iterate over the list of WebElement objects returned by findElements. This allows you to perform various actions on each anchor tag, such as clicking the link, retrieving its URL, or extracting its attributes.

In the example provided, we simply print the text of each anchor element. However, you could extend this functionality to include more complex interactions:

for (WebElement anchor : anchorElements) {
    String href = anchor.getAttribute("href"); // Get the URL of the link
    System.out.println("Link text: " + anchor.getText() + ", URL: " + href);
    anchor.click(); // Click the link (be cautious with navigation)
}
Can only iterate over an array or an instance of javalangIterable 2

Edge Cases & Gotchas

While iterating over WebElements, there are several edge cases and potential pitfalls to be aware of:

  • StaleElementReferenceException: If the DOM changes after you retrieve the elements, you may encounter this exception. It happens when the element you are trying to interact with is no longer attached to the DOM. To handle this, consider re-fetching the elements before performing actions.
  • Empty Lists: If no anchor tags are found, the list will be empty. Always check if the list is empty before iterating to avoid unnecessary errors.
  • Dynamic Content: If the page content is loaded dynamically (e.g., via AJAX), ensure that you wait for the elements to be present. Using WebDriverWait can help you manage this effectively.

Performance & Best Practices

When working with Selenium, it’s essential to consider performance and best practices to ensure your tests run smoothly and efficiently:

  • Use Explicit Waits: Instead of relying on implicit waits, use explicit waits to wait for specific conditions. This can enhance performance and reduce flaky tests.
  • Limit the Scope of Search: If you know the section of the page where the anchor tags reside, limit your search scope by using a specific parent element. This reduces the number of elements Selenium has to search through.
  • Close Unused Browser Instances: Always close the browser instances after your tests to free up resources.
  • Code Reusability: Encapsulate your element interactions in methods or classes to promote code reusability and maintainability.

Conclusion

Iterating over collections of WebElement objects is a fundamental aspect of using Selenium WebDriver effectively. By understanding how to find and interact with anchor tags, you can create robust and efficient automation scripts.

  • Use findElements to retrieve collections of elements.
  • Iterate through the elements using a for-each loop for cleaner code.
  • Be aware of edge cases such as StaleElementReferenceException and handle them appropriately.
  • Follow best practices for performance optimization and code maintainability.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

org.openqa.selenium.SessionNotCreatedException: session not created exception
Aug 20, 2023
Complete Guide to String Joiner in Java with Examples
Jul 13, 2023
NoSuchwindowException in Java
Aug 31, 2023
java.lang.IndexOutOfBoundsException
Aug 21, 2023
Previous in Java
Implicit wait V/s Explicit wait In Java
Next in Java
How to add (import) java.util.List; in eclipse
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,938 views
  • 2
    Error-An error occurred while processing your request in .… 11,273 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 235 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,459 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 162 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,497 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,232 views

On this page

🎯

Interview Prep

Ace your Java interview with curated Q&As for all levels.

View Java Interview Q&As

More in Java

  • User-defined data types in java 6285 views
  • Master Java Type Casting: A Complete Guide with Examples 6253 views
  • How to add (import) java.util.List; in eclipse 5850 views
  • java.lang.IllegalStateException: The driver executable does … 5122 views
  • Java Program to Display Fibonacci Series 4947 views
View all Java posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor