Search code examples
pythonbeautifulsoupfinance

Invalid Lateral for Float while scraping data with python and BeautifulSoup


I am trying to import price of a stock from a website. It imports the price as a string but gives me below error when I try to change it to a float:

ValueError: invalid literal for float()

This is my code.

import requests
from bs4 import BeautifulSoup

#<span class="current-price" style="color:#D22B00">1,780</span>

request = requests.get("http://www.sharesansar.com/company/EBL")

content = request.content

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

span_line = soup.find("span", {"class":"current-price", "style":"color:#D22B00"})

price = span_line.text.strip()

stock_price = float(price)

Solution

  • price = span_line.text.strip().replace(',', '')
    

    1,780 is invalid in python, get rid of the ,

    class float([x])

    If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced.