Locate all buttons on the page that have an onclick function attached to them, and

I seem to have run into an issue. I am currently working with Java and WebDriver. My goal is to navigate to , locate the item "ipod", receive 4 results, and then compare them by clicking on the "compare" button beneath each item. However, I am encountering two problems.

  1. The first problem is figuring out how to click on the "compare" button that has an onclick event attached to it.

    <button type="button" data-toggle="tooltip" title="" onclick="compare.add('48');" data-original-title="Compare this Product"><i class="fa fa-exchange"></i></butto
    n>

  2. The second problem is determining how to compare all of my search results at once.

Answer №1

Here's a sample code snippet for you to try:

    package pkYourPackage;

    import java.util.List;

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


    // http://demo.opencart.com/index.php?route=product/category&path=24

    public class OpenCart_StackOverflow {
        static WebDriver driver;
        public static void main(String[] args) {
            System.setProperty("webdriver.chrome.driver", "C:/.....put_ path/chromedriver.exe");
            driver = new ChromeDriver();

            driver.get("http://demo.opencart.com/index.php?route=product/category&path=24");
            try{Thread.sleep(5000);}catch(Exception e){}

            List<WebElement> list = driver.findElements(By.xpath("//button[contains(@data-original-title,'Compare this')]/i"));
            for(int i = 0 ; i < list.size() ; i++){
                list.get(i).click();

                try{Thread.sleep(1500);}catch(Exception e){}

            }
            try{Thread.sleep(1500);}catch(Exception e){}

            // click on 'product comparison' to compare
            ((JavascriptExecutor)driver).executeScript("arguments[0].click();",driver.findElement(By.xpath("//*[contains(text(),'product comparison')]")));
            try{Thread.sleep(10000);}catch(Exception e){}
            driver.close();
            driver.quit();

        }
    }

Answer №2

Here's my version:

  public void clickAllButtons(){

        List <WebElement> buttonElements = driver.findElements(By.xpath("//*[@data-original-title='Compare this Product']"));

    for(WebElement button: buttonElements){
        button.click();
    }

I think my solution is more concise compared to Kumar's, and it does the job effectively.

Answer №3

List<WebElement> buttonList = driver.findElements(By.xpath("//*[@data-original-title='Compare this Product']"));

Both of the following code snippets achieve the same result:

for(WebElement button : buttonList){
    button.click();
}

or you can alternatively use:

for(int index = 0 ; index < buttonList.size() ; index++)
{
    buttonList.get(index).click();
}

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

The Ruby code encountered an issue when trying to navigate to the website stored in the ENV['URL'] variable

During the execution of the test case in headless mode using the terminal, I encountered an error message as shown below. Error message Here are the specific details: I have configured chromedriver version 86 with Chrome browser version 86 and updated i ...

Scroll down only if the user is not actively scrolling

Struggling with JavaScript once again and feeling frustrated! Can someone please assist me? I am currently working on a basic chat application that retrieves content from a text file using an AJAX request. The content refreshes every few seconds, scrollin ...

What are some ways to create a flashing effect for text in HTML and JavaScript?

Although flashing text is typically prohibited in many places, my client has requested it for a project. I need to create one line of text that flashes using HTML and JavaScript. The text should appear and disappear within seconds, repeating this cycle. I ...

What is the most efficient way to use the $slice operator on a highly nested array in mongoose

I am currently working on slicing a deeply nested array. To illustrate, consider the following structure. I aim to slice this array for pagination purposes. {messages: [{ message: { members: [ {example: object, blah: blah}, {example2: object2, blah2: blah ...

Is there a way to retrieve the result produced by submitting a form with Python?

I am trying to scrape data from the following website: Here is the function I have written so far: from bs4 import BeautifulSoup as bs from selenium import webdriver def getTwitterID(name): options = webdriver.ChromeOptions() options.add_argument(&ap ...

"Encountered a floating-point issue when trying to read an Excel file with

When a user uploads an Excel file that contains decimal, string, and Unicode characters, I am encountering an issue with floating point errors when reading certain decimal values. For instance, a number like 0.15 is being read as 0.150000000002 in some c ...

There seems to be a problem with how the navbar is being displayed in ResponsiveSlides.js

I am currently using WordPress, but I have come here seeking help with a jQuery/CSS issue. I am utilizing responsiveSlides.js to create a simple slideshow, however, when viewing it here at gallery link, it appears that something is not quite right. STEPS: ...

Instructions on keeping a numerical counter at its current value for all site visitors

Recently, I integrated a number counter into my website. However, I am facing an issue where the count resets to zero whenever a new visitor accesses the site. I'd like the count to remain persistent and update based on the previous count. For instanc ...

Validating Input Field with Regular Expression in JavaScript/TypeScript to Avoid Starting with Zero

I need to create a RegEx for a text field in Angular / TypeScript that limits the user to inputting only a 1-3 digit number that does not start with 0. While it's straightforward to restrict input to just digits, I'm struggling to prevent an inpu ...

struggle with converting JSON string into an array from server

After receiving JSON data from the server, I attempted to convert it into an array using: JSON.parse(response.data.blocks) However, I encountered this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<an ...

Struggling to display Firebase Auth information resulting in 'undefined' value within React web application

When loading a user's profile page, I am trying to display their displayName and email information retrieved from Firebase Auth. I have implemented this logic within the 'componentDidMount' method by updating the state with the response dat ...

A step-by-step guide on creating an xpath for an element by using another element with Selenium WebDriver

How can I create an XPath By element that is a child of a previously defined By element? For example, let's say we have the following By Element defined: private By firstExpander = By.xpath("//div[@id = 'language-expander']"); Now, we wan ...

Adjust the size at the location of the cursor

I am having trouble understanding how to implement zoom based on mouse position using this example here: (https://stackblitz.com/edit/js-fxnmkm?file=index.js) let node, scale = 1, posX = 0, posY = 0, node = document.querySelector('.f ...

The issue with web scraping arises when the object in the Proplem list does not contain the

I am attempting to utilize Selenium for web scraping and my goal is to download images from Google. However, I am facing a few issues: I encountered an error message saying AttributeError: 'list' object has no attribute 'timeout'. I am ...

Preventing jQuery plugin from overriding default settings

I have created a jQuery plugin using the nested namespace pattern, inspired by the design template found in Addy Osmani's book. The plugin is a simple gallery and everything seems to be functioning correctly. However, I am facing an issue when attemp ...

The swf file doesn't stretch to fit the window when the height is set to 100%

Struggling with creating a flash recorder controlled by JavaScript? Trying to get the flash to fill the browser window but disappearing when setting height or width to 100%? Where am I going wrong? <div id="flashrecorder"> <object wmode="trans ...

Choose numerous dates from the calendar

Is there a way to choose multiple dates from a calendar and display them on a textview? I know there is a library called FS Calendar for ios, but is there something similar available for other platforms? ...

Interested in leveraging string functions on the information retrieved from the API?

I am trying to utilize String functions such as slice(x,y), length() on the data received from the API. To achieve this, I first converted the data to a variable called mystr using JSON.stringify(obj), but encountered an issue where the console displayed: ...

Dealing with PhantomJS: Tackling the Challenge of XMLHttpRequest Exception 101 Error

As a newcomer to JavaScript and PhantomJS, I have been encountering an issue when running myfile.js (which involves for loops) with the command phantomjs myfile.js. It consistently throws the error: NETWORK_ERR: XMLHttpRequest Exception 101: A network err ...

Converting JavaScript to JSON and saving dynamic properties

Having a basic knowledge in JavaScript, I am attempting to extract data from users and utilize it as JSON properties in the following format: <th colspan="2"><input id="dc_name" name='dc[name]'></input></th> $ ...