From c39b7eadbd4d81dda5e7ffe4c169d670483f0113 Mon Sep 17 00:00:00 2001 From: Suman <66205793+Suman2023@users.noreply.github.com> Date: Sun, 13 Aug 2023 03:28:37 +0530 Subject: [PATCH] updated the URL and HTML tags for scrapping yahoo finance (#8942) * updated the url and tags for yahoo finance * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * updated to return the error text --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- web_programming/current_stock_price.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/web_programming/current_stock_price.py b/web_programming/current_stock_price.py index df44da4ef..0c06354d8 100644 --- a/web_programming/current_stock_price.py +++ b/web_programming/current_stock_price.py @@ -3,12 +3,18 @@ from bs4 import BeautifulSoup def stock_price(symbol: str = "AAPL") -> str: - url = f"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}" - soup = BeautifulSoup(requests.get(url).text, "html.parser") - class_ = "My(6px) Pos(r) smartphone_Mt(6px)" - return soup.find("div", class_=class_).find("span").text + url = f"https://finance.yahoo.com/quote/{symbol}?p={symbol}" + yahoo_finance_source = requests.get(url, headers={"USER-AGENT": "Mozilla/5.0"}).text + soup = BeautifulSoup(yahoo_finance_source, "html.parser") + specific_fin_streamer_tag = soup.find("fin-streamer", {"data-test": "qsp-price"}) + + if specific_fin_streamer_tag: + text = specific_fin_streamer_tag.get_text() + return text + return "No tag with the specified data-test attribute found." +# Search for the symbol at https://finance.yahoo.com/lookup if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f"Current {symbol:<4} stock price is {stock_price(symbol):>8}")