Tips for selecting a value from <ul> <li> tags in Selenium with Java

I am encountering an issue with something. I am working on two equations within . The first equation is 2+2 and I validate it, then the second equation is 3+3 and I validate that as well.

The validation for the first equation is successful and I use the following code snippet:

WebElement element = driver.findElement(By.xpath("/html/body/div[3]/div[3]/ul/li[1]/p[1]"));
String title = element.getAttribute("title");
System.out.println(title);
Assert.assertEquals(title, "4");

This test passes without any issues.

However, for the second equation, I cannot reuse the xpath mentioned above because it still refers to the value 4.

Any suggestions on how to approach this?

Here is the code snippet provided:

<ul>
<li>
<p title="6" class="r">=&nbsp;6</p>
<p data-inp="3+3" title="3+3" class="l">3+3</p>
</li>

<li>
<p title="4" class="r">=&nbsp;4</p>
<p data-inp="2+2" title="2+2" class="l">2+2</p>
</li>

</ul>

I intend to locate the element with "title=6" to perform assertion on the equation.

Answer №1

When using the assertEquals method, remember that the expected value should be the first argument.

For example:

package tests;

import java.util.List;

import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

// custom class with driver init
import selenium.ChromeDriverSetup;

public class Web20calc extends ChromeDriverSetup {

    public static void main(String[] args) {
        
        // wrapped driver init
        WebDriver driver = startChromeDriver();
        
        driver.get("https://web2.0calc.com/");
        
        // handling cookie consent
        driver.switchTo().activeElement();
        driver.findElement(By.xpath("//*[@id=\"precmpdialog\"]/div/div/div[2]/form/div/div[2]/button")).click();
        
        WebElement btn2 = driver.findElement(By.id("Btn2"));
        WebElement btn3 = driver.findElement(By.id("Btn3"));
        WebElement btnPlus = driver.findElement(By.id("BtnPlus"));
        WebElement btnCalc = driver.findElement(By.id("BtnCalc"));
        WebElement btnClear = driver.findElement(By.id("BtnClear"));        
        WebElement showHistory = driver.findElement(By.xpath("//*[@id=\"hist\"]/button[2]"));
        
        // perform calculations
        btn2.click();
        btnPlus.click();
        btn2.click();
        btnCalc.click();
        
        btnClear.click();
        
        btn3.click();
        btnPlus.click();
        btn3.click();
        btnCalc.click();
        
        showHistory.click();
        
        Assert.assertEquals("= 6", getHistoryResult(driver, 0));
        Assert.assertEquals("= 4", getHistoryResult(driver, 1));
        Assert.assertEquals(null, getHistoryResult(driver, 2));

        driver.quit();
    }
    
    public static String getHistoryResult(WebDriver driver, Integer lineNumber) {
        String result = null;
        WebElement histframe = driver.findElement(By.id("histframe"));
        WebElement ul = histframe.findElement(By.tagName("ul"));
        List<WebElement> lis = ul.findElements(By.tagName("li"));
        Integer lisSize = lis.size();
        if (lineNumber > lisSize - 1) {
            System.out.println("Linenumber " + lineNumber + " is out of range. Size of List is: " + lisSize);
        }
        else {
            WebElement li = lis.get(lineNumber);
            WebElement p = li.findElement(By.tagName("p"));
            result = p.getText();
            System.out.println("Result in line " + lineNumber + ": " + result);
        }
        return result;      
    }

}

Output:

ChromeDriver version 111.0.5563.64 (c710e93d5b63b7095afe8c2c17df34408078439d-refs/branch-heads/5563@{#995}) running on port 36109
Only local connections are allowed.
Please refer to https://chromedriver.chromium.org/security-considerations for tips on ensuring ChromeDriver safety.
ChromeDriver started successfully.
[1681997766.849][WARNING]: This version of ChromeDriver has not been tested with Chrome version 112.
March 20, 2023 3:36:06 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Result in line 0: = 6
Result in line 1: = 4
Linenumber 2 is out of range. Size of List is: 2

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

Automatically appending textarea value in HTML tag upon form submission via JQuery

When a form is submitted through JQuery, the HTML tag automatically adds textarea value. This is my JQuery code: $('#calling').click(function() { $('#myform').submit(); }); Within my form, there is a textarea element: <textar ...

Is there a way to implement fixed scrolling on a website?

I'm interested in implementing fixed scrolling on a webpage similar to the effect used here: . When you scroll on that website, it smoothly transitions to the next div. I believe there is some JavaScript involved, but I am not sure how to achieve thi ...

Tips for aligning a menu that expands from the side to the center

I'm trying to center the menu on my webpage, but the issue is that it's stretching from the sides. Here's a sample image of the menu layout: I'm struggling to figure out how to fill the empty space on the left side of the menu. ...

What could be preventing the background image from displaying properly?

I had the idea to create a game where players have to flip cards to reveal what's on the back, but I'm struggling to get the background image to display properly. As a newcomer to Vue, I'm not sure if I made a mistake somewhere. My intuition ...

Is there a way to customize the color of a MUI styled component?

I have a customized MUI component that displays a circular badge in green. const StyledGreenBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', ...

Tips for including background pictures in the jumbotron using bootstrap

I've recently delved into bootstrap just a couple of days ago. Now, I'm encountering an issue where I can't seem to add a background image to my entire webpage or even the jumbotron specifically. I've attempted to directly input the pa ...

Tips for refreshing the page upon Geolocation request

I am working on a HTML5 project that requests geolocation from the user. Here is an image of what it looks like: https://i.sstatic.net/o6yCj.png My main query is: Is there a way to refresh the page automatically once the user grants permission to share t ...

Migrating a game built on SDL 2.0 to the Android platform

I'm currently working on a C/C++ game using SDL 2.0 and I am interested in porting it to mobile platforms, specifically Android but possibly other platforms as well. Although the game was originally coded for Windows, no Windows-specific libraries or ...

Troubleshooting Safari compatibility with CSS transitions: a first attempt

Greetings everyone, I am a complete beginner here so please bear with me. After looking at some examples, I have managed to create a start/stop slowdown feature. Here is the JSFiddle link for reference .small-wheel, .big-wheel{ transition: all 2s ease ...

Designing in Ionic 3.x: Implementing Ion-Icon with a gradient backdrop (ion-chip)

Is there a way to add a gradient background to an icon? I attempted to nest the ion-icon within an ion-chip, like so: <ion-chip class="my-chip"> <ion-icon name="basket></ion-icon> </ion-chip Then, in the .css file: ...

Centering an unordered list and ensuring the image is responsive across different screen sizes are both top priorities for this design

Currently, I am working on an HTML project through freecode academy and encountering some obstacles. My goal is to center align the unordered list and make sure that the image responds well to various screen sizes. Please feel free to leave comments with ...

Ways to utilize the ::after pseudo class with ElementRef within Angular

Is it possible to manipulate the background-color of the ::after pseudo selector for the specified element using Angular? @ViewChild('infobubble', { read: ElementRef }) infoBubbleElement: ElementRef; ngAfterViewInit(): void { const el ...

Should I utilize a single form or one for each table row in asp.net mvc?

While working on a project, I caught myself in a coding dilemma: <table> <tr> <th>Code</th> <th>Enabled</th> <th>Percentage</th> <th>Amount</th> <th>Start&l ...

Exploring the ins and outs of webpage loading speed

I am working on writing JavaScript code that includes a button to open a webpage of my choice. I now want to understand how to detect when the page I called is finished loading. Any suggestions or ideas on this topic? I apologize if my explanation was no ...

Using Selenium to extract information from a scrolling table

My goal is to extract data from the website gate.io by gathering a list of all the coins/tokens displayed in the left table. The purpose is to be able to click on each coin/token and retrieve the long/short ratio information located on the right side of ...

What is the best way to create a JQuery click event that applies to every button on my webpage?

I am working on a website settings page where logged-in users can edit the content displayed on the public page. I have a form that uses AJAX to update the content when submitted. My main question is how to modify the code so it can determine which text b ...

Crafting CSS for styling input type file elements

My attempts to style the input type file with CSS have been unsuccessful. In my current code, the "choose file" button is displaying above my styled button. How can I use CSS to remove this? I am aiming to only display a blue colored button for uploading ...

Comparing Embedded and Linked JS/CSS

In my experience, I understand the advantages of using linked CSS over embedded and inline styles for better maintainability and modularity. However, I have come across information suggesting that in certain mobile web development applications, it may be m ...

Looking for a website to conduct load testing? You'll need to log in first in order to access

I am in the process of developing an Automated Testing Python Project to conduct comprehensive testing on a website. This project involves executing Functionality, Accessibility, and Load Testing on the website, with detailed reporting of the outcomes. The ...

Is it possible to combine two conditions using CSS?

Hello, I have a question about CSS. In my navigation bar, I have 3 links with different styles: #p1 { font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 45px; font-weight: bolder; color: #999999; text-dec ...