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

Ensure that all content in the table rows remains visible, even in a table with unusually lengthy cells

My HTML table is structured like this: +-------------+-------------+----------+ | Single line | Single line | Very, | | | | very | | | | long | | | | text, | | ...

Bypass Security Check in Firefox

I am facing issues while trying to automate selenium on a website owned by a third party. When an authentication prompt like this appears in Firefox, Selenium fails: You can see a similar situation when clicking the Display Image button here Is there a ...

When viewing HTML emails in dark mode on iOS Gmail, the CSS appears to be inverted

While sending an HTML email from a nodejs app, I encountered an issue with Gmail on iOS where elements with background-color or color properties were getting reversed. This was most noticeable on black and white elements. Despite consulting various guides ...

Tips for extracting data from an Angular object using the *ngFor directive

https://i.stack.imgur.com/ai7g1.png The JSON structure displayed in the image above is what I am working with. My goal is to extract the value associated with the key name. This is the approach I have taken so far: <span *ngFor="let outlet of pr ...

Oops! There seems to be an issue with the argument "handle" in window handling using Selenium and Java on a Linux system. It appears that the argument must be a string

I need to run test cases in a CI pipeline where the VM is operating on a Linux platform. When using Selenium for multiple window handling, the switchTo() method throws an exception. The exception message is: org.openqa.selenium.WebDriverException: invali ...

The Zoom CSS property seems to be experiencing some issues on the Firefox browser

After researching the issue, I discovered several solutions involving css3 transition techniques. Currently, I have been using {zoom:1.5} for all of my buttons. However, this method does not work on Firefox. When attempting to implement the transition pro ...

The fillOpacity and opacity properties appear to be malfunctioning

Note: While I understand that image masking can solve my issue, I prefer not to use it as it would require me to use my image as a background and could present accessibility challenges. I am specifically looking for solutions involving clip-path. Issue: T ...

The viewport width in NextJS does not extend across the entire screen on mobile devices

I'm currently tackling a challenge with my NextJS Website project. It's the first time this issue has arisen for me. Typically, I set the body width to 100% or 100vw and everything works smoothly. However, upon switching to a mobile device, I not ...

Leveraging em units in jQuery Script

I'm currently in the process of building a website and I'm facing an issue with converting measurements to em's. The script that I have reused from a previous project only seems to work with pixels, despite my efforts to make it compatible w ...

Execute the maven project containing a profile that includes the JUnit runner

My project's pom.xml includes <systemPropertyVariables> and <profiles>. Currently, when I run it as a Maven build, I use -DXXX for system property variables and -PXXX for profiles in the goal. Now, I want to execute this as a JUnit test in ...

Utilizing the same browser session across various scenarios

In the following code, I am attempting to utilize the same browser session in different test cases. However, upon execution, it is observed that two separate browser sessions are being opened for each test case. Any suggestions on how to resolve this iss ...

Ways to implement schema.org and JSON-LD for data labeling on a homepage of a website

After reading extensively on utilizing schema.org to mark structured data, I have a couple of questions. Firstly, is it advisable to use json-ld considering that it's relatively new and not fully supported yet? Secondly, how can I implement schema.org ...

Ways to evenly distribute children in a row using CSS

https://i.stack.imgur.com/HmziN.png The image above showcases the desired effect I am aiming for. It is important to note that the width of the container div may vary. The child elements should have consistent spacing between each other as well as the le ...

Executing horizontal scrolling on a website by clicking a button with Selenium

As a newcomer to Selenium, I have been experimenting with different ways to simplify my tasks. Take a look at this URL - I've been attempting to click the arrow button in the top right corner of the page under the popular category, but so far I have ...

What is the best way to eliminate the border in IE edge that surrounds special characters?

Here is the current appearance of the cross button in IE/Edge: And here is how it is supposed to look: Upon inspecting the CSS, it reveals that the #10006 html character has a color code of FFF: I am seeking assistance on how to remove the black border ...

Saving Ruby Selenium Screenshot to a designated File directory

Struggling with saving a screenshot to a specific file location: I currently have code that saves a screenshot to the original file location of my workspace: driver.save_screenshot("screenshot.png") What I want is to save the screenshot in its own folde ...

Ensure the padding and margin are both set to 0 when using inline styles

As someone who is not a designer, I attempted to send an email from PHP. In order to do so, I took a template and converted all styles to inline. However, I am unsure of where to include the universal margin and padding style in the template. *{margin:0px ...

Curious about how to swap the positions of these two divs?

After wrapping them in divs and adding inline-block to both elements to display them side by side, I'm now exploring options to switch their positions. Specifically, I'd like the right element to be on the left. Any ideas on how to achieve this? ...

Unable to expand or collapse rows in ng-table

Looking to implement an expand and collapse feature for ng-table, where clicking on a row should expand it to show more detail. However, currently all rows expand on click. Any ideas on how to achieve this? Any assistance would be greatly appreciated, tha ...

Ways to access a global ArrayList in a separate method

I recently started using selenium and implemented Page Factory. Here is the issue I am facing: At the class level, I have declared a public arraylist (let's call it List1) which stores values from method1, and it works fine when printed within the sa ...