Choosing an element with Selenium based on another element's attributes

My current project involves using Selenium and Java to interact with a table. I am trying to create a selector that can locate a specific column in the table and perform a right-click action on it. The challenge I am facing is that while it's easy to identify the column based on unique lstype values, I am unable to directly right-click on it. As a workaround, I need to click on the box directly below the column.

Here is an example of what the table looks like: Table

And here is the simplified HTML structure:

<div class="head">
    <table>
        <tbody>
            <tr>
                <td class="game" lstype="124"></td>
                <td class="game" lstype="245"></td>
                <td class="game" lstype="873"></td>
            </tr>
        </tbody>
    </table>
</div>
<div class="body">
    <table id="extractBody">
        <tbody>
            <tr>
                <td class="game"></td>
                <td class="game"></td>
                <td class="game"></td>
            </tr>
        </tbody>
    </table>
</div>

The td elements in the "head" section correspond to the header boxes (highlighted in green), while those in the "body" section are the clickable elements.

I am struggling to figure out how to target the lower boxes based on the lstype values present in the header boxes. Even though I have only shown 3 columns in this example, there are many more in the actual table along with rows.

Any guidance on the use of xpaths or any other approach would be greatly appreciated as I have not been successful with my previous attempts.

Thank you for your assistance!

Answer №1

Assuming you can identify the row using a specific xpath, and that the rows are sorted. In this case, you can use the following XPath to locate the desired row:

.//table[@id='extractBody']//tr/td[count(//td[@lstype='124']/preceding-sibling::td) + 1]

This XPath counts the number of TD elements before the current node, adds 1 to it (considering your current node as the second one), and then locates the element in that column with:

.//table[@id='extractBody']//tr/td[desiredcount]

You can then interact with or click on the identified element.

Answer №2

If you're looking to automate tasks, there are two methods you can try. The first method involves using a Mozilla plugin called Selenium IDE. This plugin will track all your actions like clicks and movements, allowing you to export the recorded data in different formats such as Java classes.

The second method is by adding unique identifiers to each checkbox in the body element and referencing them when needed. While using XPath might be more complex, it can be a fallback option if the other methods fail.

Answer №3

To simplify the process, start by locating all td elements that have the game class.

List<WebElement> gameElements = webDriver.findElements(By.cssSelector("td.game");

Next, iterate through these elements to find the target element. Once found, add half of the total list size to its index and click on it.

int count = 0;
for(WebElement element: gameElements){
  if (element.getAttribute("lstype").equals({searchTerm})) {
    gameElements.get(count + (gameElement.size()/2)).click();
  }
  count++;
}

This method assumes an equal number of elements in both tables for accurate results.

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

Maintaining checked items in their original state while searching for another one in ion-searchbar can be achieved by properly handling

My goal is to maintain the checked items as checked when searching for another item in ion-searchbar. While I have managed to keep the checked items, the checkmark icon does not stay checked. What I aim for is to retain the checked state of all food items ...

Interactive pop-up text box for data cells in a table

I have implemented a textarea in the td cell of each row within column 3 to store description specific to that row. The goal is for the current description in the td's textarea to be copied over to the textarea located inside #div_toggle when the user ...

I prefer to disable the toggle feature if the target remains unchanged

My goal is to create a step-by-step ordering system using the data-id="x" attribute to determine which content should be visible when selected. I want to make sure that if two elements have the same data-id, clicking on one will deselect the other. Any su ...

Assign a specific style to Fancybox links and buttons for managing the functions of 'next', 'previous', and 'close'

Utilizing the following jQuery script to hide a div whenever anything that does not have the class 'click' is clicked (used for empty space and certain other divs). $(document).click(function (event) { if (!$(event.target).hasClass('cli ...

What is the best way to implement the useCallback hook in Svelte?

When utilizing the useCallback hook in React, my code block appears like this. However, I am now looking to use the same function in Svelte but want to incorporate it within a useCallback hook. Are there any alternatives for achieving this in Svelte? con ...

Having trouble interacting with the 'button' in selenium webdriver using Java

In this code snippet, I am trying to pinpoint the location of an href button: <a class="btn grey-edit" data-original-title="Login" data-placement="top" data-toggle="tooltip" href="/users/userlogin/3"> <i class="fa fa-sign-in" aria-hidden="true"& ...

Utilizing an external SCSS or CSS file with Material UI in React: A step-by-step guide

Encountering issues with external CSS files in my React project that uses Material UI components. Despite creating a CSS file for each component in the react components folder, they fail to load upon hard reloading the site. I prefer using external CSS ov ...

Methods to fill a data table cell

I have recently created a table and I am facing an issue in populating the tds cells using JavaScript. The data for the table is coming from the server. Here's my table: <table id="report" class="infoRecurso" id='testExportId' style="wid ...

magnify within a div with a set width

Looking for a way to make a div both zoomable and scrollable within a fixed-width container using transform: scale(aScaleRatio) for zooming in/out. Check out this demo for achieving the zoom effect. However, the inner div seems to have trouble aligning to ...

The website on iPad automatically zooms in upon opening and then increases the zoom level even further when a specific button is tapped

I recently coded a website using html, css, and js. It seems to work perfectly on all devices except for the iPad. Interestingly, when I use the iPad emulator in Google Chrome, everything appears normal. However, when I open the website on an actual iPad, ...

The div content is aligning at the baseline rather than the middle

The social icons on my website are currently displaying at 40x40, with the text appearing below them. I am looking to center the text within the icons themselves. Any tips on how I can achieve this? Your help is much appreciated! Check out the fiddle here ...

Display a color box popup when a radio button is selected

I need help implementing a functionality where a popup modal opens when a specific radio button is checked. I have tried using colorbox with an anchor, but it doesn't seem to work with radio buttons. Does anyone have any sample code or suggestions? T ...

Manage the application of CSS media queries using JavaScript

Is there a method to control which CSS media query a browser follows using JavaScript? As an example, let's say we have the following CSS: p { color: red; } @media (max-width: 320px) { p { color: blue; } } @media (max-width: 480px) { p { col ...

What is the best way to modify the underline style of a tab in Material UI?

I'm trying to customize the underline of: https://i.stack.imgur.com/J2R1z.png Currently, I am using material ui version 4.12.3 The code snippet for generating my tabs is below: function renderTabs(): JSX.Element { return ( <Tabs className={cla ...

Steps for executing ASP code pulled from the database

In my ASP project, I have a single page where clicking on different links retrieves corresponding HTML from the database and loads it. Some links are always present on the page (static HTML), while other divs display dynamic content fetched from the DB. Wi ...

Confirm the email address using the autocomplete feature in the field

I'm currently utilizing Material UI to design an autocomplete field with multiple inputs that gives users the option to either choose from existing email addresses or input their own. An example of what I'm trying to achieve can be seen here: ht ...

jQuery: Locate and eliminate any images in the text that appear after a specific group of tags if no images are present

Currently, I am in the process of developing a feed reader specifically designed to parse the Google News Feed. You can view and test the code on this Fiddle. My main challenge lies in removing titles and sources from the descriptions. Through my explorati ...

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 ...

HTML - Lists Not Displaying Properly in Numerical Order

My goal with HTML is to: Produce 2 Numbered Lists Nest an Unordered List within Each Ordered List and add elements inside Unfortunately, my numbering isn't displaying correctly. Instead of 1. 2. etc., I'm seeing 1. 1. Below is the code I am u ...

Navigational tabs have been implemented in multiple independent sets, eliminating the need for multiple scripts to manage hiding content on click events

In a previous inquiry, I sought guidance on achieving a specific tab functionality like the one depicted below: https://i.stack.imgur.com/s2Gm8.png The query led to an insightful suggestion from @BradleyCoupland, who provided the following code snippet: ...