What is the best way to increase incrementally with Selenium POM?

Can someone help me figure out how to select two quantities of the same item in Selenium POM using a for loop? My current solution is not working, and I need to know how to increment twice in POM.

Below is the file where my page objects are stored:

package pageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

public class TTPStorePage {

    WebDriver driver;

    public TTPStorePage(WebDriver driver) {
        this.driver = driver;
    }

    By size= By.id("size");
    By quantity= By.id("quantity_5cb788738ee07");
    By reset= By.className("reset_variations");
    By submit=By.cssSelector("button[type='submit']");
    By remove=By.xpath("//a[contains(@data-gtm4wp_product_id,'TS-TTP']");
    By contents=By.className("cart-contents");


    public void selectSize(int index) {
        Select drop = new Select(driver.findElement(size));
        drop.selectByIndex(index);
    }

    // Having trouble with this method.
    public void quantityItem() {
        for(int i=0;i<2;i++) {
            driver.findElement(quantity).sendKeys(Keys.ARROW_UP);
        }
    }

    public WebElement resetItems() {
        return driver.findElement(reset);
    }


    public WebElement submitButton() {
        return driver.findElement(submit);
    }

    public WebElement removeItem() {
        return driver.findElement(remove);
    }

    public WebElement cartContents() {
        return driver.findElement(contents);
    }

}

Here's the file that contains my test cases. In this file, I am facing difficulties trying to correctly increment my items by two.

package SimpleProgrammer;

import java.io.IOException;
import org.testng.annotations.Test;
import resources.Base;
import pageObjects.TTPProductPage;
import pageObjects.TTPStorePage;

public class PurchaseApplication extends Base {

    @Test
    public void BuyItem() throws IOException {
        driver=initializeDriver();
        driver.get("https://simpleprogrammer.com/store/products/trust-the-process-t-shirt/");

        TTPProductPage pp= new TTPProductPage(driver);
        pp.TTPButton().click();
        TTPStorePage sp = new TTPStorePage(driver);
        sp.selectSize(4);
        // This is where I'm struggling
        sp.quantityItem();
    }

}

Answer №1

If you are dealing with an INPUT field, make sure to clear the input field before using sendKeys to provide a value. It is essential to use the name attribute that is unique rather than relying on non-unique ID attributes.

WebElement element = driver.findElement(By.name("quantity"));
element.clear();
element.sendKeys("2");

Answer №2

Upon analyzing the webpage you are attempting to reach, I have noticed that the spinner located within the TTPStorePageclass under the identifier quantity has a dynamic id. This id changes each time the page is loaded, requiring an adjustment in your locator strategy.

I recommend trying one of the following locators for identifying the quantity:

Css Selector:

By quantity = By.cssSelector("div.quantity > input");

XPath:

By quantity = By.xpath("//div[@class='quantity']/input");

In addition, within the quantityItem method, the for loop may not be necessary as you can directly set the desired value using the sendKeys method on the input element.

Consider implementing the following code:

public void quantityItem() {
    driver.findElement(quantity).clear();
    driver.findElement(quantity).sendKeys("3");
    // Pressing the up arrow twice should change the spinner value to 3
}

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

Saving and retrieving information within a Python script file

I am looking to automate the weekly download of torrents. Specifically, I would like to create a dictionary that stores the names of TV series, along with their respective seasons and episodes. For example: series = {'Last.Week.Tonight':{'S ...

When using the Selenium IDE with the Selblocks plugin, one may encounter the need to evaluate a variable within an if command to determine its truthiness

Currently, I am in the process of writing a script where I define two variables. In this script, I need to evaluate one of the variables to determine if it is true in order to execute certain actions. However, when I use the "verify element present" functi ...

The replaceAll function is not functioning properly when dealing with escape characters in

​ I'm currently working on converting XML data into JSON format using Java. However, I am encountering an error when trying to parse the data. The error is related to a specific character: &#xD; JSON.parse: bad control character in string liter ...

Data from the server isn't loading in Angular2

I have successfully developed a basic Java app using REST that returns a string value when accessed through a REST client. However, I am now facing an issue in fetching the string value using an Http REST client in Angular2. I have set up a service to retr ...

Managing class values with Selenium - Manipulating and updating classes

In the program I'm working on, there is a need to toggle which element receives the class value of "selected". <div class="countryValues"> <div data-val="" >USA and Canada</div> <div data-val="US" >USA - All< ...

Obtain a PDF file using Selenium and Python in the Chrome browser

Having some trouble downloading a pdf using Chrome with Selenium and Python. I read that turning on a setting in Chrome could solve this issue. At the start of my code, I attempted to enable this setting using Selenium driver.get('chrome://settings/ ...

Guide on how to correctly read and input highchart numbers into selectors using Selenium WebDriver with Python

Exploring a web application that implements highcharts functionality. The selectors are structured like this, with the highchart number varying for each chart. #highcharts-3 >div:nth-child(1) > span > div > span Inquiring about a method to ac ...

Methods for effectively redirecting a Java ResponseWriter

I am looking for a way to view the output of my ResponseWriter directly in standard output for debugging purposes. Unfortunately, since the response will be handled by JavaScript, I am unable to see the output there. Is there a simple solution to redirect ...

Encountered a JSON parsing error when trying to import data into MongoDB

I've encountered an issue while attempting to import a json file into MongoDB using Java drivers. The error message I received is as follows: Exception in thread "main" com.mongodb.util.JSONParseException: at com.mongodb.util.JSONParser.read ...

Using Python with Selenium to extract text from a webpage

How can I utilize Python Selenium to extract the text ": Sahih al-Bukhari 248"? The code snippet provided does not seem to be working as expected. reference = find_element_by_xpath(".//div[3]/table/tbody/tr[1]/td[2]").text print reference See HTML excer ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...

What is the best way to ensure that selenium chrome opens in fullscreen mode?

Can selenium be configured to open in fullscreen mode without the need for additional code? I am asking this question as a requirement for one of my projects, where an element will only load properly if the browser is in fullscreen mode. ...

The sequence of the selenium tests is not running as expected

Despite using @FixMethodOrder(MethodSorters.NAME_ASCENDING), my tests are not running in the desired order. I have two tests: The first test is named aTest_Login() The second test is named bTest_CreateContact() Occasionally, the second test is executed b ...

What causes Google Chrome to have trouble interacting with elements on occasions?

As I delve into learning Selenium, I am faced with the challenge of creating an automated script to navigate to the Gmail registration page and input all the necessary details. To summarize my objectives: Launch Google Chrome with the base URL set to ...

Using Selenium to interact with website links and extract content from bubbles

I need to extract information about the courses listed at this link. My approach involves clicking on each course link, retrieving the description that appears in a bubble, and then closing the bubble to avoid it overlapping with other links. The issue I ...

Restricting Jackson Serialization/Deserialization Depth for every class

I experimented with using the CustomJSONSerializer as suggested in this discussion on Stack Overflow. However, I encountered the following error: com.fasterxml.jackson.databind.JsonMappingException: object is not an instance of declaring class (through ...

Running selenium and behave on a local port: A step-by-step guide

Having successfully integrated Selenium and Behave to interact with external websites, I am now faced with the challenge of making them work together with my fullstack python application running on local port 8000. When attempting to run Selenium code to a ...

Python is a powerful language that can be used to capture and analyze

I am using a WebDriver through Selenium to automate opening a browser, directing it to an IP address, performing various tasks, and then closing it. My goal is to track all URLs accessed during this process. This includes any ads that are displayed, CSS c ...

Executing Selenium tests with TestNG framework and Jenkins

To automate the execution of Selenium tests written in TestNG framework using Jenkins, a command is configured within a Jenkins job (Freestyle project). java -cp J:\taf\testng\*;J:\taf\workspace\TestNGExamples\bin;J:&bso ...

The issue is that Allure is not accurately logging failures when encountering exceptions like nosuchelementexception

Even in the event of failure in krGlobalPage.softAssertionTestCall1(softAssertion);, krGlobalPage.softAssertionTestCall2(softAssertion); must still be executed because ...