Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

couldn't scrap the price out of a HTML code

I have the HTML code below:

<span class="price">
    <span class="woocommerce-Price-amount amount">
        <bdi>
             <span class="woocommerce-Price-currencySymbol">R</span>
             1 579
             <sup>00</sup>
        </bdi>
    </span>
</span>

I need to extract the price from there using python in format "1579.00" as a float. how can I do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To get the price amount as float you can use next example:

import re
from bs4 import BeautifulSoup

html_doc = """<span class="price">
    <span class="woocommerce-Price-amount amount">
        <bdi>
             <span class="woocommerce-Price-currencySymbol">R</span>
             1 579
             <sup>00</sup>
        </bdi>
    </span>
</span>"""

soup = BeautifulSoup(html_doc, "html.parser")

price = soup.select_one(".amount").text
price = float("".join(re.findall(r"\d+", price))) / 100
print(price)

Prints:

1579.0

Or:

soup.select_one(".woocommerce-Price-currencySymbol").extract()
price = float(
    soup.select_one(".amount")
    .get_text(strip=True, separator=".")
    .replace(" ", "")
)
print(price)

Prints:

1579.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading