From 6198c72651f13e0cb748d1ad529753efa9a70959 Mon Sep 17 00:00:00 2001 From: lighting9999 Date: Sat, 5 Jul 2025 17:34:37 +0800 Subject: [PATCH] Fix build error current_stock_price.py --- web_programming/current_stock_price.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/web_programming/current_stock_price.py b/web_programming/current_stock_price.py index 16b0b6772a9c..b25962cf5007 100644 --- a/web_programming/current_stock_price.py +++ b/web_programming/current_stock_price.py @@ -5,10 +5,12 @@ # "httpx", # ] # /// +from doctest import testmod -import httpx +import requests from bs4 import BeautifulSoup + """ Get the HTML code of finance yahoo and select the current qsp-price Current AAPL stock price is 228.43 @@ -28,20 +30,22 @@ def stock_price(symbol: str = "AAPL") -> str: True """ url = f"https://finance.yahoo.com/quote/{symbol}?p={symbol}" - yahoo_finance_source = httpx.get( - url, headers={"USER-AGENT": "Mozilla/5.0"}, timeout=10, follow_redirects=True - ).text + try: + yahoo_finance_source = requests.get( + url, headers={"USER-AGENT": "Mozilla/5.0"}, timeout=10 + ).text + except requests.exceptions.RequestException: + return "- " + soup = BeautifulSoup(yahoo_finance_source, "html.parser") if specific_fin_streamer_tag := soup.find("span", {"data-testid": "qsp-price"}): return specific_fin_streamer_tag.get_text() - return "No tag with the specified data-testid attribute found." + return "- " # Search for the symbol at https://finance.yahoo.com/lookup if __name__ == "__main__": - from doctest import testmod - testmod() for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split():