-1

How do I get this code to loop for other stocks? For example, I want it to repeat and show stocks like Telsa, Amazon, Apple all in one executution? In my code, it only shows one stock and I want it to display multiple stocks.

Code:

import requests
from bs4 import BeautifulSoup

def create_url():
    url = f'https://finance.yahoo.com/quote/TSLA'
    return url

def get_html(url):
    header = {"User Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'}
    response = requests.get(url, headers = header)

    if response.status_code == 200:
        return response.text
    else:
        return None


def parse_data(html):

    soup = BeautifulSoup(html,'html.parser')
    name = soup.find('h1', {'class': 'D(ib) Fz(18px)'}).text
    price = soup.select_one('#quote-header-info > div.My(6px).Pos(r).smartphone_Mt(6px).W(100%) > div.D(ib).Va(m).Maw(65%).Ov(h) > div.D(ib).Mend(20px) > fin-streamer.Fw(b).Fz(36px).Mb(-4px).D(ib)').text
    stock_data = {
        'name':name,
        'price':price,
    }

    return stock_data

def main():
    url = create_url()
    # get html
    html = get_html(url)
    
    data = parse_data(html)
    
    #return data

    print(data) 


if __name__ == '__main__':
    main()
  • 1
    How about making a list of URLs and iterating over it using a `for` loop? – mkrieger1 Mar 11 '22 at 22:27
  • Yep thats fine, im not sure how to do it though – Ryan Marinas Mar 11 '22 at 22:29
  • first create function which get one symbol and get data from server, and next use `for symbol in ["TSLA", "Amazon", "Apple"]: ...` to run it for many symbols. – furas Mar 11 '22 at 22:47
  • 1
    it seems you use `f-string` so you should know how to create url for variable `f'https://finance.yahoo.com/quote/{symbol}'` – furas Mar 11 '22 at 22:49
  • "I'm not sure how to do it, though" Start by reading about lists and loops in python. You might want to work some smaller examples before figuring out how it works in your larger project. – Code-Apprentice Mar 11 '22 at 22:51

1 Answers1

2

Try changing your create_url to take one parameter, which will be the stock you want to query, like so:

def create_url(ticker):
    url = 'https://finance.yahoo.com/quote/' + ticker
    return url

Then, you can create a list of tickers in your main function and call the function for each ticker.

def main():
    tickers = [“AAPL”, “TSLA”]

    for ticker in tickers:
        url = create_url(ticker)
        # get html
        html = get_html(url)
    
        data = parse_data(html)

        print(data)
Radu
  • 183
  • 2
  • 8