Obtaining the text of a span tag within a div using Selenium in C#

<div id="uniqueSummaryID" class="custom-text" data-reactid=".0.0.0.3.0.0.1.0.0.0.0.$unique_key_25.1.1.0">
<span data-reactid=".0.0.0.3.0.0.1.0.0.0.0.$unique_key_25.1.1.0.0">5</span>
<span data-reactid=".0.0.0.3.0.0.1.0.0.0.0.$unique_key_25.1.1.0.1">/</span>
<span data-reactid=".0.0.0.3.0.0.1.0.0.0.0.$unique_key_25.1.1.0.2">15</span>
</div>

How can I extract the values '5' and '15' from the above HTML structure by targeting the div with id 'uniqueSummaryID', ideally without relying on XPath in Selenium using C#?

Answer №1

To target specific elements on a webpage, you can employ a CSS selector:

driver.FindElements(By.CssSelector("#targetSummaryCount > span"))

This code snippet will select all span elements that are directly nested under the element with the id="targetSummaryCount".

Answer №2

Here is the provided solution in Java. Could you please assist me in converting it to C#?

    WebElement divSummary = driver.findElementById("targetSummaryCount");
    List<WebElement> targetKeys = divSummary.findElements(By.tagName("span"));
    // To retrieve the first and last elements
    targetKeys.get(0);
    targetKeys.get(targetKeys.size()-1);

    // To maintain a queue of elements with text 0 or 20
    HashMap <Integer, List<WebElement>> elementmap = new HashMap <Integer, List<WebElement>>();
    List<WebElement> webElements1 = new ArrayList<WebElement>();
    List<WebElement> webElements2 = new ArrayList<WebElement>();
    for (WebElement elem : targetKeys){
        if(elem.getText().trim().equals("0")){
            webElements1.add(elem);
        }
        else if (elem.getText().trim().equals("20")){
            webElements2.add(elem);
        }
    }
    elementmap.put(0,webElements1);
    elementmap.put(20,webElements1);
    // elementmap.get(0) contains all span tags under the target Summary Count div tag
    // elementmap.get(20) contains all span tags under the target Summary Count div tag

Answer №3

If you want to retrieve the values "0" and "20" using XPath, you can use the following code:

string num1 = driver.FindElementByXPath("//div[@id='targetSummaryCount']/span[1]").Text;
string num2 = driver.FindElementByXPath("//div[@id='targetSummaryCount']/span[3]").Text;

// Alternatively,
var elements = driver.FindElementsByXPath("//div[@id='targetSummaryCount']/span");
string num1 = elements[0].Text;
string num2 = elements[2].Text;

You can also achieve this with a Css Selector like so:

string num1 = driver.FindElementByCssSelector("#targetSummaryCount > span:nth-child(1)").Text;
string num2 = driver.FindElementByCssSelector("#targetSummaryCount > span:nth-child(3)").Text;

// Or using even CSS selector
var elements = driver.FindElementsByCssSelector("#targetSummaryCount > span:nth-child(even)");
string num1 = elements[0].Text;
string num2 = elements[1].Text;

Answer №4

Give this a shot.

        var count = driver.FindElements(By.XPath("//*[@id='targetSummaryCount']/span")).Count;
        var finalResult = "";
        for (int index = 0; index < count; index++)
        {
            var text = driver.FindElement(By.XPath("//*[@id='targetSummaryCount']/span[" + index + "]")).Text;

            if (text != "/")
            {
                finalResult += "span:" + index + " text:" + finalResult;
            }
        }

Answer №5

One approach to consider is accessing the span element that is a descendant of the div with the id targetSummaryCount and contains either the text 0 or 20.

var span_00 = driver.FindElementByXPath("//div[@id='targetSummaryCount']/span[text()='0']");

var span_20 = driver.FindElementByXPath("//div[@id='targetSummaryCount']/span[text()='20']");

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

Troubleshooting problems with encoding in a PHP contact form

As a newcomer to PHP, HTML, and programming in general, I am working on creating a contact form using PHP and HTML. So far, everything is functioning properly and I am able to receive emails. However, there is one issue - when I try to fill out the form in ...

Update the jQuery script tag with new content - rewrite everything

I am facing an issue with jquery. I need to change the link to src only when "document.write" is present. Below is my code: myscript.js document.write("TEST ABCD"); test.html <html> <body> <button id="example">click me</button&g ...

I am constantly encountering the NoSuchElementException when attempting to access. Is there a solution to this issue?

As I delve into the world of web scraping and automation, I've recently begun exploring Selenium. However, I find myself a bit perplexed about what steps to take next. Despite searching for similar queries here, none seem to provide a solution. Where ...

When you hit a certain point on the website, the scrolling momentarily pauses

Upon refreshing the page and scrolling down, I notice that the website experiences a brief lag for a few milliseconds before continuing as normal. Oddly enough, this issue only occurs after refreshing the page. Any suggestions on how to resolve this? Th ...

Tips for implementing a hover transition effect in the navigation menu

I have a specific query regarding a particular issue that I am unsure how to address but would like to implement on my website. 1) My requirement is that when the parent li element has a child, I want the navigation to remain in a hovered state with the s ...

Is there a way to eliminate the space between the gray background and the right edge of the browser window?

body{ font-family:'Montserrat'; } .content{ background-color:#d9d9d9; } p.dates{ display:inline-block; font-weight:800; margin-right:20px; width:120px; text-align:center; margin-top:0; margin-bott ...

What could be causing my insertRow function to inject empty cells into my table?

I am facing an issue with adding the results of a fetch request into a table as a new row. Strangely, when I click the button to trigger this function for the first time, it adds an empty row instead of the desired data. However, on subsequent clicks, the ...

The functionality similar to an "Extension Property" is not supported in .Net

Imagine a hierarchy represented by a "Person" class, where the ParentPerson property allows for hierarchical representation at any depth level. While it doesn't have to be structured this way specifically, think of this need regardless of implementati ...

Launching a browser in Incognito mode in Selenium using CRTL + Shift + N doesn't seem to be functioning properly within the Sauce Labs environment

When running tests that require logging in with different roles on the application, I typically use CTRL+Shift+N for incognito mode on my local machine. However, when testing on Saucelabs, this method doesn't work as it is unable to open incognito mod ...

Allow-Origin-Control, handler.php for emails, and form validation script

I encountered a strange bug recently. There's been some issues with the HTML5 template I downloaded, specifically related to the contact form and MailHandler.php file. Despite having both files in the same directory, when inspecting element in Chrome, ...

What is the best way to extract text using Selenium in Java?

My goal is to extract the text $1.00 from the HTML code snippet below (I already have the xpath, so no need to worry about that). Let's assume the xpath is //*[@id="price-string"] <strong id="price-string">$1.00</strong> ...

Enhancing JSON data by incorporating new key-value pairs

I need help converting a CSV file into a JSON file using C#. The issue I am facing is that the JSON generated contains only values without any keys. I want to convert it into a key => value format for better organization. Below is my current code: stat ...

Steps for generating a collection of rows from a table

I'm working with a webpage that has a table containing data. My goal is to extract the rows of the table and turn them into a list. Once I have the list, I plan to process each item individually. Each row in the table is marked with an attribute na ...

Create a visually appealing collage using CSS without the need for traditional IMG tags

I'm currently working on a fun little project. My goal is to create a photo grid in HTML5 that displays 3x4 pictures (without using Divs) and adding all the images via CSS, meaning no img tag in the HTML file. The challenge is to make this grid respo ...

Disregard validation of the view if the element includes the attributes `display: none`

Displayed below is an HTML text input that is designed to toggle visibility using jQuery's slideUp and slideDown functions, which change the display attribute to none with animation. My current challenge is that I do not want to validate the element w ...

the mobile website is not properly aligned on a horizontal axis

As I work on creating a mobile version of my website, I've come across a challenge: The entire site fits perfectly on the computer at a browser width of 480px, but when viewed on my mobile phone (regardless of the browser used), it leaves space on the ...

The width of the TD element does not affect the grid

<div id="unique-example" class="k-unique-content"> <table id="unique-grid" style="float: left; position: relative"> <thead> <tr> <th width ="410px"data-field="UniqueFileName">Unique File Name ...

Why are my video files exhibiting inconsistent behavior?

I've encountered an issue with the code on my website where I'm trying to display a 40-second video. The video converter I used seems to have added extra video types, which may be causing the problem. Here's what the HTML code looks like: ...

Is there a way for me to collaborate on a footer control with a different website?

Is it possible to seamlessly incorporate a footer from one website into another? Ideally, I want the footer HTML (and styles) to be dynamically inserted into different web pages. The common workaround is using an iframe, but this causes navigation issues ...

Locate the element using xpath with a dynamic variable included

I am looking to extract the 'Code' information from . The xpaths for 'Code' are listed below: ABP //*[@id="post-2"]/div/table/tbody/tr[1]/td[1] AX1 //*[@id="post-2"]/div/table/tbody/tr[2]/td[1] It's noted that the xpath patter ...