Bouza
Bouza

Reputation: 11

Simple Web Scraper returning no data

Im trying to scrape data from a webpage but its returning ["F"] ["F"] which is what it should do if no data has been retrieved. Please see Code below

`

import pandas as pd
import datetime
import requests
from requests.exceptions import ConnectionError
from bs4 import BeautifulSoup

def web_content_div(web_content, class_path):
    web_content_div = web_content.find_all('div', {"class": class_path})
    try:
        spans = web_content_div[0].find_all('span')
        texts =[span.get_text() for span in spans]
    except IndexError:
        texts=[]
        return texts

def real_time_price(stock_code):
    url = 'https://finance.yahoo.com/quote/' + stock_code + '?p=' + stock_code + '%27&.tsrc=fin-srch'
    # 'https://finance.yahoo.com/quote/' + stock_code + '?p=' + stock_code + '&.tsrc=fin-srch'
    try:
        r = requests.get(url)
        web_content = BeautifulSoup(r.text, 'lxml')
        texts = web_content_div(web_content, 'My(6px) Pos(r) smarthphone_Mt(6px) W(100&%')
        if texts != []:
           price, change = texts[0], texts[1] 
        else:
            price, change = ["F"], ["F"]
    except ConnectionError:
        price, change = [""], [""]

    return price, change
    

Stock = ["BRK-B"]

print(real_time_price("BRK-B"))`

Upvotes: 1

Views: 51

Answers (1)

Jesse Ambler
Jesse Ambler

Reputation: 36

Your class_path doesn't exist due to a couple of typos. Website in question references "My(6px) Pos(r) smartphone_Mt(6px) W(100%)", which I believe is what you're targeting.

Upvotes: 1

Related Questions