What is the method for retrieving the non-strike price amount in selenium via xpath?

This is the link to the webpage I am attempting to automate:

My goal is to extract the value of the non-strikethrough price (currently $ 20.00) using Selenium and an XPath locator.

The following HTML snippet contains the element I am targeting:

<div class="course row" data-scroll-reveal=""
     style="-webkit-transform: translatey(24px);transform: translatey(24px);opacity: 0;-webkit-transition: -webkit-transform 0.66s ease-in-out 0s,  opacity 0.66s ease-in-out 0s;transition: transform 0.66s ease-in-out 0s,  opacity 0.66s ease-in-out 0s;-webkit-perspective: 1000;-webkit-backface-visibility: hidden;"
     data-scroll-reveal-initialized="true">
    <div class="col-sm-4">
        <a href="course-detail.php?id=130&amp;t=websecurity-testing-for-beginners-qa-knowledge-to-next-level">
            <img src="/courses-description.php?show=130" alt="websecurity-testing-for-beginners-qa-knowledge-to-next-level" class="img-responsive" width="186" height="123">
        </a>
    </div>
    <div class="col-sm-8">
        <div class="row">
            <div class="col-md-9 col-sm-8">
                <h3>
                    <a href="course-detail.php?id=130&amp;t=websecurity-testing-for-beginners-qa-knowledge-to-next-level">
                        WebSecurity Testing for Beginners-QA knowledge to next level
                    </a>
                </h3>
                <div class="meta">
                    <span><i class="fa fa-user"></i><a href="#">Rahul Shetty</a></span>
                    <span><i class="fa fa-file-text"></i>60 Lessons</span>
                    <span><i class="fa fa-folder"></i><a href="#">Penetration testing</a></span>
                </div>
            </div>
            <div class="col-md-3 col-sm-4 price">
                <del style="font-size:15px;color:#aaa">$ 85.00</del>
                <br>
                $ 20.00
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <p class="course-desc">
                    Course Launch Date : Aug 30th 2015 -Its Time to Protect our Websites from Security Attacks This Tutorial will give all the weapons you needed to investigate and
                    unlock the Security Holes in the Web applicationCourse lectures are conceptually driven with root level explanations and bring you to the level where you can
                    bring out the security bugsCourse Contents: Basics of Security Testing...
                    <br>
                    <a href="course-detail.php?id=130&amp;t=websecurity-testing-for-beginners-qa-knowledge-to-next-level">
                        Read More
                        <i class="fa fa-angle-right"></i>
                    </a>
                </p>
            </div>
        </div>
    </div>
    <div class="col-md-12">
        <hr>
    </div>
</div>

I have attempted various methods but have not yet found a solution.

Answer №1

Learn how to extract the price information ($20.00) using this Python method specifically designed for that purpose. Please note that this method may not work in all scenarios, especially when dealing with both struck-through and non-struck-through prices.

def get_text_exclude_children(element):
    return driver.execute_script(
        """
        var parent = arguments[0];
        var child = parent.firstChild;
        var textValue = "";
        while(child) {
            if (child.nodeType === Node.TEXT_NODE)
                    textValue += child.textContent;
                    child = child.nextSibling;
        }
        return textValue;""",
        element).strip()

Follow these steps to implement the method:

element = driver.find_element_by_xpath("(//div[@class='col-md-3 col-sm-4 price'])[1]")
price = get_text_exclude_children(element)

Answer №2

The original price displayed as $ 20.00 is considered a text node. To extract this text, you can utilize the following method:

  • Method in JavaScript:

    WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='course row']//div[contains(@class, 'price')]")));
    String myText = ((JavascriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", element).toString();
    System.out.println(myText);
    
  • Output on Console:

    $ 20.00
    

Answer №3

query=//section[@id='content']/div/div/div/div/div/div[2]/div/div[2]

Answer №4

To effectively address your query, more information is needed as there are various items on the webpage with both strike-through and non-strike-through values.

For a general approach, you can utilize the following code to target multiple blocks containing prices. For a more specific targeting, a slightly complex locator specifying the item along with the price block will be necessary. If focusing on the first price block on the page, the following code will suffice:

//*[contains(@class,'price')]

This essentially translates to the CSS selector below (which is less intricate):

.price

However, the markup poses a challenge as shown here:

<div class="col-md-3 col-sm-4 price">
    <del style="font-size:15px;color:#aaa">$ 85.00</del>
    <br>
    $ 20.00
</div>

In strict XPath implementation, you could employ a syntax like this:

//*[contains(@class,'price')]/text()

It's worth noting that Selenium doesn't support binding a text node directly into a WebElement. This means while the aforementioned Xpath works in a browser context, it won't function as a locator for identifying a specific element (as it targets a text node).

An effective resolution would involve raising a bug report and requesting the developer to encapsulate the unstruck amount within its own element (e.g., enclose it with a <span> tag).

If looking for a workaround, you may resort to fetching the inner HTML of the element using the following method:

WebElement price = driver.findElement(By.cssSelector(".price"));
String elementHTML = price.getAttribute("innerHTML");

The extracted string in 'elementHTML' will contain the content displayed above. Subsequently, you'll need to parse the string to eliminate the initial two lines (though not an elegant or dependable solution).

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 behavior of JavaScript may vary when running in the IE deployment environment compared to running in debugging tools like Visual

UPDATE: After debugging in IE, it seems that the "setSelectionRange" function is not supported. It's strange that it works in Visual Studio but not outside of it. The JavaScript fails at that line when running in IE, which raises the question: how can ...

Ways to identify local storage when a user visits the page for the first time using jQuery

As a beginner in the world of local storage in Jquery, I am looking to implement a feature on my Bootstrap 4 accordion. The desired functionality is as follows: If a user is visiting the page for the first time, all accordions should be open by default ...

Pulling information from the ultimate outcome page with Selenium and Visual Basic for Applications

I am currently working on enhancing a process to automate copying and pasting data from a government website to an Excel sheet. The site I am dealing with is quite complex, which adds to the challenge. Extracting data from this specific website has been a ...

Storing file paths as string variables in Angular: a quick guide

I'm working with this line of code that selects all the files in a folder. <input type="file" id="filepicker" name="fileList" (change)="saveFolderLocation($event)" webkitdirectory/> My goal is to determin ...

most effective method for establishing a relationship between a variable and its corresponding identification number

When retrieving results from a database with a simple PHP while loop, one of the data pieces includes a number that links to another table where the corresponding value is stored. While there are various ways to link this information and display the relate ...

Which is better for a jQuery/Ajax Login Box: JSONP or CORS?

To create a login box that meets the specified criteria, the following must be taken into consideration: Develop it as a versatile UI Component that can be utilized in various sections of a website Allow for multiple instances of this component to coexis ...

Automatically identify the appropriate data type using a type hint mechanism

Can data be interpreted differently based on a 'type-field'? I am currently loading data from the same file with known type definitions. The current approach displays all fields, but I would like to automatically determine which type is applicab ...

Incorporate PNG files with pre-defined labels in a React element

In my application, there is a collection of PNG images with filenames consisting of only 2 letters like aa.png, ab.png, ac.png, and so on. Additionally, there is an API endpoint that retrieves an array of objects with a property "name" containing 3 letter ...

Generating an MD5 hash for a UTF16LE string in Javascript (with no BOM and excluding 0-byte at the end) - Illustrated with a C#

I've been trying to figure out how to get an MD5 Hash of a UTF16-LE encoded string in JavaScript for the past few days. I have a method in C# as an example, but I'm not sure how to replicate it in JavaScript. Example: public string GetMD5Hash ( ...

What is the mechanism through which a nested function within an event handler obtains the event object?

How is the e object available to the nested function inside handleClick2 when only the input object is passed? Is this related to the concept of Lexical Environment? handleClick2 = (input) => (e) => { this.setState({ [input]: e.target.va ...

What is the best way to identify which JavaScript code is triggering or managing an event?

In the development of an HTML5 application framework designed for businesses to use on their intranet and extranet sites, a SAP JEE application server is utilized. The framework incorporates the grid system known as "Semantic UI" along with various JavaScr ...

Tips for maintaining the functionality of IFrame?

I am encountering an issue with tracking clicks on a div that contains an IFrame. While the tracking functionality works, it seems to interfere with the IFrame's functionality. Is there a way to resolve this and make both functionalities work simultan ...

Issue with preventDefault not functioning correctly within a Bootstrap popover when trying to submit a

I am facing an issue with a bootstrap popover element containing a form. Even though I use preventDefault() when the form is submitted, it does not actually prevent the submit action. Interestingly, when I replace the popover with a modal, the functional ...

Using Javascript to access element that was dynamically created by using getElementById

Exploring Javascript has been a fun hobby of mine, but I've hit a roadblock when trying to access dynamically created elements with another function. Here's the scenario: I have a link that generates dropdown selects with options when clicked. T ...

Issue with Selenium not displaying inner text content from div tag

I am currently using selenium to extract data from a website called Mergent Archives, specifically trying to retrieve the innerText from the following element: <div class="x-paging-info" id="ext-gen200">Displaying reports 1 - 15 o ...

The interface 'children: string' does not share any properties with the type 'IntrinsicAttributes'.ts(2559)

When I export the component, the value from the input email does not appear as a VALUE property. How can I collect the text written in this exported component in my code? NOTE: I am working on developing a design system using STORYBOOK. export const Login ...

The innovative way Vue.js revolutionizes HTML updates within a Websocket onmessage event

I'm new to Vue.js and I'm trying to capture data inside the onmessage event of a websocket and update an HTML component (either a span or div). While console.log or alert functions work in onmessage, I couldn't get it to update the span. Th ...

Selenium driver initialization results in connection time out

A custom Django management command has been created to interface with BrowserStack using Selenium for running integration tests. This was necessary due to compatibility issues between AskBot and the Django testing framework on the site. The script can be f ...

A guide to querying JSON data in a backend database with JavaScript

My backend JSON DB is hosted on http://localhost:3000/user and contains the following data: db.json { "user": [ { "id": 1, "name": "Stephen", "profile": "[Unsplash URL Placehol ...

Error occurred in the main thread: org.openqa.selenium.InvalidElementStateException:

Today, I encountered an issue while trying to send input string to the search text box on a Chrome browser: // attempting to search for a text in Google WebDriverWait wait3 = new WebDriverWait(driver1,30); WebElement textBox = wait3.until(ExpectedConditio ...