Clicking a button with Java Selenium

While trying to navigate all the pages on a website, I encountered an issue where after scrolling to the second page, I received an exception stating that the element does not exist on the page. Upon further investigation, I realized that the CSS selector for the elements changed at different points in the website's structure. Sometimes it appears as

WebElement nextButton = driver.findElement(By.cssSelector("#pagination-head>a>div>span.hidden-xs.hidden-sm"));
, while other times it is
WebElement nextButton = driver.findElement(By.cssSelector("#pagination-head > a:nth-child(3) > div > span.hidden-xs.hidden-sm"));
. My question is, how can I handle this scenario in Selenium? I looked into methods to check if a given WebElement exists or not, but unfortunately, I couldn't find any :/

Answer №1

Here is a helpful CSS selector that will work for either path:

WebElement next = driver.findElement(By.cssSelector("#pagination-head span.hidden-xs.hidden-sm"));

Answer №2

In the case where you are limited to just two choices, one possibility is to utilize a workaround using an if/else statement.

One approach could be to establish a boolean variable that assesses whether or not the element can be located via your initial findElement method. If this evaluation yields true, proceed with executing the first block of code; otherwise, switch to the second block of code.

Answer №3

If you want to ensure that your automation script can locate the next button reliably, it's best to use xpath instead of relying solely on specific locators. By using xpath, even if the locator changes on a later page, your code will still be able to find and interact with the next button successfully. Below is a sample code snippet demonstrating how to locate and click on the next button:

WebElement nextButton = driver.findElement(By.xpath(".//*[contains(text(),'Replace this text with the actual text displayed on your next button')]"));
nextButton.click();

Simply replace 'Replace this text with the actual text displayed on your next button' in the code above with the exact text shown on your next button. This code will then perform a click operation on the element matching the specified text.

I hope this explanation proves useful for your automation tasks!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

incorporating video content onto a webpage

Let me provide more details for better understanding. Currently, the website is not operational yet. Once it's live, I'll be hosting it on a platform like YouTube. The issue I encountered was when trying to embed a video using the code below: & ...

Issue with nth-child selector not functioning as expected in unordered list

I have a straightforward <nav> setup with an unordered list inside: nav { position: absolute; right: 0px; white-space: nowrap; } nav ul { padding: 0; margin: 0; } nav ul li { clear: both; white-space: nowrap; color: white; displa ...

The gradle build encountered an issue with a method signature in Java, specifically with hashmap.getOrDefault not being applicable

While attempting to build with Gradle, an unexpected error occurred. This error is puzzling as Strings are considered Objects: No method signature found for: java.util.HashMap.getOrDefault() with arguments: (java.lang.String, java.lang.String) values: [pr ...

Error encountered in Hibernate when attempting to cast java.lang.Boolean as java.lang.String while utilizing JDK 1.7

I'm having trouble with Hibernate. Currently using Hibernate version 3.2.6 and JDK 1.7.0_21 Could this issue be due to compatibility between the JDK and Hibernate version? This problem seems to occur randomly. I haven't been able to identify c ...

Is there a way to automatically close a created div by clicking anywhere outside of it?

I'm facing an issue with a dynamically created div that I want to close by clicking outside of it. However, when I try to achieve this functionality, the div closes immediately as soon as it is opened. closediv(); } function closediv() { d ...

What is the process for detaching and attaching click animations using the on() method?

I am encountering an issue with a recursive loop that executes a simple animation. These animations are controlled by the page load and clicking on controls .carousel_item. Click here for live sample JSFiddles for demonstration purposes Challenge: The pr ...

What is the best way to dynamically create list items for an unordered list using ASP.NET?

In my development project, I am facing an issue where an error panel needs to be displayed on a page in case of errors. Currently, the error messages are being appended to a string and then added to a label. However, dealing with multiple errors makes this ...

Achieving perfect center alignment for the middle element with flexbox

When it comes to the layout below, my objective is to always keep the middle item centered within the container div. This means that the left and right items should be aligned to the far left and right of the container respectively. The current styling fo ...

What is the best way to adjust a div's size according to the device's screen dimensions?

I'm in the process of developing a web app that will be used on iOS devices, specifically targeting both iPhone 4 and iPhone 5. During my development phase using an iPhone 5 device, everything seemed to fit perfectly and work seamlessly. However, when ...

Utilize JavaScript to iterate through a JSON object and retrieve the indices that meet the specified criteria

While I found a previous answer that somewhat addresses my issue, I am seeking guidance on how to return an array of the indexes where a specific value appears. For example, if **18A38** is the target value, it should return the positions [1,3]. The sampl ...

Utilizing Firefox profiles with Selenium

Attempting to automate browser actions using Selenium Webdriver and Python on my Windows 10 system has presented me with a challenge. The Firefox window started by Selenium does not recognize that I am already logged in, causing the target site to redirect ...

The input group addon is not displaying properly in the Mozilla browser

I am presenting the following data in a table: <table class="neo-table"> <tr> <td>Day of final discharge home</td> <td>{{ form_widget(form.mHomeDischargeDay, {'id': 'M_Home_discharge_day', ' ...

CSS code completion in PhpStorm is not functioning properly for Twig extended templates

Currently, I am working with PhpStorm 2016.1 and facing an issue with file autocomplete. The scenario is as follows: @mycss .style {color : red} @base.html.twig [...] <link rel="stylesheet" href="/vendor/mycss.css" /> <!--HERE AUTOCOMPLETE OF s ...

Modify vanilla JavaScript carousel for compatibility with Internet Explorer

I am currently in the process of creating a website that incorporates a carousel similar to the one found at the following link: https://codepen.io/queflojera/pen/RwwLbEY?editors=1010 At the moment, the carousel functions smoothly on opera, chrome, edge ...

What sets npm node-sass apart from npm sass?

Recently, I discovered that the recommended approach is to utilize @use rather than @import in sass. However, it appears that using npm sass instead of npm node-sass is necessary for this. Can you clarify the distinction between these two? Also, why do @ ...

Merging Fewer with Visual Studio 2012

Combining all Less files into a single stylesheet? After following the instructions in the above link, I have successfully merged my Less files together for easier CSS reading during development. However, I would like to ensure that end users only need to ...

Using JavaScript to create CSS animations triggered on hover

Looking for a CSS Animation that will play forward once when the mouse enters a specific div, and then play in reverse when the mouse leaves. Check out my JsFiddle here. The div with the class ".item" should trigger the mouse enter event. The animation co ...

Are there any faster options than Selenium?

URL - I'm currently using the selenium method to extract data from the provided URL, but it's quite slow. Is there a way I can achieve the same result using just the request library? The specific text I aim to extract is shown in this image htt ...

Translate CSS into JavaScript while maintaining selector understanding

I am interested in developing a tool that can read a .css file and generate a function that will accept an array of class names as input and output the corresponding styles for an element with those classes, represented as a JavaScript object. This tool wo ...

Avoiding Ajax overload/server collapse in an Arduino/ESP8266 setting

I've recently been delving into Arduino programming to host an HTML/CSS/JavaScript webpage on an Adafruit HUZZAH ESP8266 breakout board. Please pardon any unconventional methods I may be using. My approach involves utilizing Ajax to update pressure g ...