Utilizing WebElement.findElements() in Selenium to refine search outcomes

After iterating through a list of WebElements, which I refer to as 'graphs', and finding descendants within each graph, I am encountering an issue where similar descendants from different graphs are being included in the results. Currently, I am using By.cssSelector() to find these elements. Additionally, I need to access information from the parent of these descendants, making it difficult to isolate them using only css selectors.

Does anyone have an explanation for why this might be happening? Is there a method to first find the child elements and then trace back to their respective parents?

I was considering using a selector like graph.findElements(By.cssSelector(".child:parent"), but this type of selector is not valid in CSS.

If there is any confusion in my explanation, please let me know.

Thanks!

EDIT_1: To provide more context, here is the hierarchy I am dealing with:

<div class="graph">
    <...several nested tags...>
        <div class="parent">
            <div class="child" />
            <div class="child" />
        </div>
    <...several nested tags.../>
</div>

... (repeated for multiple 'graph' elements)

When using graph.findElements(By.cssSelector(".parent")), it returns a list of 3 WebElements when I actually only need 1. On the other hand, using graph.findElements(By.cssSelector(".child")) correctly returns a list of 2 WebElements.

EDIT_2:

Here is the specific information I need to extract:

From the parent element: I need to retrieve the class name, as it acts as a boolean value determining the element's appearance.

From the first child element: I require its visual attributes, determined by the boolean class name, as well as a single unique class name for easy identification.

From the second child element: I need to extract its textual content, without relying on an ID or class name for locating it.

Answer №1

Do you have to use By.cssSelector(".parent")? You might want to think about using By.className("parent") instead for the graph web element within your loop. Another option could be to try using By.xpath(".//parent") on the graph element. While Xpath may not be as quick or tidy, it only adds milliseconds to the process, so it's worth considering if it helps you locate the desired object. Although className() should do the trick, personally I lean towards Xpath as it allows me to specify the exact element I need (especially useful on websites with repeated class names).

Answer №2

After analyzing your inquiry, I believe I have a clearer understanding of what you need assistance with. It seems like you have explored one approach, but it's uncertain how extensively you pursued it.

List<WebElement> graphs = driver.findElements(By.cssSelector("div.graph"));
for (WebElement graph : graphs)
{
    List<WebElement> parents = graph.findElements(By.cssSelector("div.parent"));
    for (WebElement parent : parents)
    {
        List<WebElement> children = parent.findElements(By.cssSelector("div.child"));
        for (WebElement child : children)
        {
            if (child.getText().trim().equals("abc123"))
            {
                // The desired element has been located... perform an action on the parent
                System.out.println(parent.getText().trim());
                // Consider breaking out of the nested loops at some point
            }
        }
    }
}

Alternatively, you can directly target the specific child element you require using a CSS Selector, for instance:

driver.findElements(By.cssSelector("div.graph div.child"));

Iterate through these elements until you identify the one you need, then execute a

foundElement.findElement(By.xpath(".."));

To obtain the parent element. While somewhat cumbersome, this method will effectively achieve the desired outcome.

Answer №3

After some experimentation, I managed to resolve the issue simply by changing the CSS selector I was using.

graph.findElements(By.cssSelector("table:nth-child(2) td"));

Initially, this code snippet returned a list of 3 WebElements, which was incorrect.

graph.findElements(By.cssSelector("table.mar10t td"));

However, when I switched to this CSS selector, I received a list of 2 WebElements, which was the correct outcome.

Interestingly, when I tested both CSS selector paths in Firebug, they produced the same results...

If anyone can shed light on why the first selector was incorrect, please share your insights in the comments. I'm eager to learn more about this behavior.

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 Less compiler (lessc) encounters an issue on a fresh operating system. ([TypeError: undefined is not a function])

After setting up my new development environment on Windows 10, I encountered an issue with less. Following the instructions on lesscss.org, I installed less using: npm install -g less The installation process completed without any errors. However, when ...

drag and drop feature paired with additional textarea below

query 1: How can I make the bottom-left textarea move together with the top-left textarea when I drag it down? query 2: What is the solution to prevent the left-bottom textarea from moving when I drag down the top-right textarea? http://jsfiddle.net/4BX6 ...

Troubleshooting a mapping problem with CSS elements

While building my website, I have successfully mapped the elements by ID for all alphabet letters except A. When clicking on the letter A, it does not go to the respective elements. Can anyone please help me find a solution? Visit this link for reference ...

WordPress having trouble rendering the stylesheet code

I am facing an issue with Wordpress where my CSS file is not loading properly. The stylesheet contains a rule to center the header image, but for some reason it's not working. I've also tried adding a margin-left of 100px, but that doesn't s ...

Elements on the page appear and disappear as you scroll down

Whenever my scroll reaches the bottom of element B, I want my hidden sticky element to appear. And when I scroll back up to the top of element B, the sticky element should be hidden again. Here are my codes: https://i.sstatic.net/J49dT.jpg HTML <htm ...

Managing the placement of the expanded autocomplete input in Material-UI

Whenever I use the autocomplete fields on my website, I've observed an interesting behavior. When I select multiple options, the height of the input increases significantly, causing everything below it to shift downward like this. Is there a way to m ...

The HTML Style for implementing HighChart title text does not work when exporting files

I have inserted the <br/> and &nbsp; HTML tags into the HighChart titles. The style changes successfully appear in the chart view, but unfortunately, when exported as PNG or JPEG images, the text style fails to apply in the resulting images. To s ...

Even after applying the CSS property "resize:none" to my HTML textarea, I still find it to be adjustable in size when viewed in the Opera browser

I'm currently working on customizing my HTML page and I want to ensure that all text inputs are consistent in size. I attempted to use the text-area selector in CSS, but it didn't seem to work correctly in Opera. The resize handle disappeared in ...

Is there a way to verify that a form field has been completed?

Currently, I am grappling with a method to clear a field if a specific field is filled in and vice versa. This form identifies urgent care locations based on the information provided by users. The required entries include the name of the urgent care facil ...

Selenium can be quite patient when trying to locate an element

Currently, I am developing software that scans website source codes to locate email addresses. However, when the source code is extensive, it takes a considerable amount of time to search through it. Is there a way for me to set a specific time limit for ...

Having trouble applying CSS styles to an element using JavaScript

Hello, I have an unordered list with some list elements and I am trying to apply a CSS style to highlight the selected list element. However, the style is not taking effect as expected. function HighlightSelectedElement(ctrl) { var list = document.ge ...

Python's webdriver for data scraping techniques

codesample I am facing an issue while trying to interact with a button using Firefox, Python, and Webdriver. Every time I encounter the following error message: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .pull- ...

The webpage design presents a challenge for Selenium as it obstructs the selection of text

This issue is really testing my patience: I am attempting to retrieve the response from a Pandorabot using Selenium. However, even though I can input text and trigger the bot's reply, the formatting of its webpage makes it incredibly challenging to se ...

What are some best practices for implementing responsive design using CSS @media queries with makeStyles in React.js Material UI?

const useStyles = makeStyles(theme => ({ wrapper: { width: "300px" }, text: { width: "100%" }, button: { width: "100%", marginTop: theme.spacing(1) }, select: { width: "100%", marginTop: theme.spacing(1) } })); I ...

AngularJS and Bootstrap carousel combined for a dynamic multi-item per slide display

Currently, I am utilizing Bootstrap to showcase a carousel on my website, where multiple items are displayed per slide as demonstrated in this example. The use of static images has yielded satisfactory results, as evidenced by the jsFiddle example found he ...

Is there a way to prevent the slide-out bar from automatically hiding when selecting an item from its list?

I am facing an issue with my dashboard that has a slideout sidebar. Whenever I press the toggle button, the sidebar slides out as expected. However, when I click on any tab within the sidebar, it hides again. I only want it to hide when toggled. My code is ...

Attempting to change the primary color in Bootstrap is ineffective following a button click

I have been attempting to customize the primary color of Bootstrap 5 using SCSS. Everything works perfectly until I click a button that opens an external link. Below is the content of my SCSS file: $primary: #ae217aff; @import "../node_modules/boots ...

What is the best way to increase the space between table columns in CSS?

I'm struggling to increase the space between the columns in a simple table with two columns. The column-gap property doesn't seem to be working for me. Any suggestions on how I can achieve this? JSFiddle #t td { -webkit-column-g ...

Executing Selenium tests on DynamicForm elements within SmartGWT: A comprehensive guide

Exploring the world of Selenium in conjunction with GWT and SmartGWT components. Struggling to figure out how to effectively test SmartGWT's DynamicForms components such as TextItem and SelectItem. These composite elements lack identifier attributes ...

A guide to verifying the breadcrumb order using selenium

I have a header that is set up as First / Second / Third in the form of breadcrumbs. I am looking to verify if these elements are displayed in the correct order using Selenium and want to ensure the code is optimal. <ol class = "breadcrumb" <li ...