Ghofran Challouf
Ghofran Challouf

Reputation: 47

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?

Upvotes: 1

Views: 90

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195438

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

Upvotes: 2

Related Questions