Я кодирую проект, в котором пользователь вводит тикер акции, а затем программа собирает информацию об этой акции с определенного веб-сайта и возвращает данные.У меня есть полностью рабочая программа, но у меня возникает проблема: если пользователь вводит несуществующий тикер, программа выдает ошибку и перестает работать.Как я могу это исправить?Вот соответствующий сегмент кода для справки:
def make_url(ticker_symbol): #making a function that returns a URL when a ticker is passed through it
return "https://www.bloomberg.com/quote/%s:US" % ticker_symbol
def Calculation():
lower_stock = Ticker_entry.get()
stock = lower_stock.upper()
url = make_url(stock)
page = requests.get(url) #requesting the HTML code of the website
soup = BeautifulSoup(page.content, "lxml") #Converting the HTML code of the website into a beautifulsoup object
Как мне сделать так, чтобы, если пользователь вводит несуществующий запас, программа выдает сообщение «Пожалуйста, введите действительный тикер акции».?
Вот полный код для справки:
import matplotlib
import sys
from requests.exceptions import ConnectionError
import matplotlib.dates as dates
from tkinter import *
from bs4 import BeautifulSoup
import requests
import lxml
import datetime
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt
#Graphical User Interface
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
root = Tk()
root.title("Stock Price")
root.configure(background="white")
Calculator = Frame(root, height=300, width=700, bg="white").grid(column=0, row=2)
title = Label(root, bg="white", text="Stock Price Calculator", font="Sans 25 bold", fg="black").grid(row=0)
Stock_ticker = Label(root, text="Input stock ticker here:", font="Sans 18 bold")
Stock_ticker.place(x=7, y=60)
Ticker_entry = Entry(root, width=10)
Ticker_entry.place(x=235, y=64)
Stock_price = Label(root, text="Current stock price:", font="Sans 15")
Stock_price.place(x=7, y=100)
Stock_price_output = Entry(root, width=10)
Stock_price_output.place(x=160, y=100)
Stock_price_day = Label(root, text="Opening price for the day:", font="Sans 15")
Stock_price_day.place(x=7, y=140)
Stock_price_day_output = Entry(root, width=10)
Stock_price_day_output.place(x=195, y=141)
Last_closing_price = Label(root, text="Last closing price:", font="Sans 15")
Last_closing_price.place(x=7, y=180)
Last_closing_price_output = Entry(root, width=10)
Last_closing_price_output.place(x=180, y=181)
Stock_news = Label(root, text="News about stock:", font="Sans 15")
Stock_news.place(x=7, y=220)
Stock_news_output1 = Entry(root, width=50)
Stock_news_output1.place(x=150, y=221)
Stock_news_output2 = Entry(root, width=50)
Stock_news_output2.place(x=150, y=242)
Stock_news_output3 = Entry(root, width=50)
Stock_news_output3.place(x=150, y=263)
Submit = Button(root, text="Submit", font="Sans 14", command = lambda: Calculation())
Submit.place(x=165, y=300)
Reset = Button(root, text="Reset", font="Sans 14", command = lambda: Cleaning(Ticker_entry, Stock_price_output, Stock_price_day_output, Last_closing_price_output, Stock_news_output1, Stock_news_output2, Stock_news_output3))
Reset.place(x=250, y=300)
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def make_url(ticker_symbol): #making a function that returns a URL when a ticker is passed through it
return "https://www.bloomberg.com/quote/%s:US" % ticker_symbol
def make_historical_url(ticker_symbol):
return "https://www.nasdaq.com/symbol/%s/historical" % ticker_symbol
def Calculation():
lower_stock = Ticker_entry.get()
stock = lower_stock.upper()
url = make_url(stock)
page = requests.get(url) #requesting the HTML code of the website
soup = BeautifulSoup(page.content, "lxml") #Converting the HTML code of the website into a beautifulsoup object
#Finding and inserting the current price
current_number = soup.find('span', attrs={'class':'priceText__1853e8a5'})
current_price = current_number.text
Stock_price_output.insert(0, "$")
Stock_price_output.insert(1, current_price)
#Finding and inserting opening price
opening_number = soup.find('div', attrs={'class':'value__b93f12ea'})
opening_price = opening_number.text
Stock_price_day_output.insert(0, "$")
Stock_price_day_output.insert(1, opening_price)
#Finding and inserting last closing price
closing_numbers = soup.find_all('div', attrs={'class':'value__b93f12ea'})
closing_number = closing_numbers[1]
closing_price = closing_number.text
Last_closing_price_output.insert(0, "$")
Last_closing_price_output.insert(1, closing_price)
#Finding and inserting news
news = soup.find_all('div', attrs={'class':'headline__07dbac92'})
news_1 = news[1].text
news_2 = news[2].text
news_3 = news[3].text
Stock_news_output1.insert(0, news_1)
Stock_news_output2.insert(0, news_2)
Stock_news_output3.insert(0, news_3)
#Drawing the graph of the stock
historical_url = make_historical_url(stock)
historical_page = requests.get(historical_url)
soup_2 = BeautifulSoup(historical_page.content, "lxml")
all_numbers = soup_2.find('tbody')
all_nums = all_numbers.text
all_nums_1 = all_nums.split()
length = len(all_nums_1)
prices = []
dates = []
current_time = datetime.datetime.now()
current_time_format = current_time.strftime("%m/%d/%Y")
all_nums_1[0] = current_time_format
for t in range(int(length/6)):
index = t * 6 + 4
prices.append(all_nums_1[index])
for t in range(int(length/6)):
index = t * 6
date_str = all_nums_1[index]
format_str = '%m/%d/%Y'
datetime_object = datetime.datetime.strptime(date_str, format_str)
dates.append(datetime_object)
final_dates = matplotlib.dates.date2num(dates)
#plotting the graph of the last 3 months of stock price
plt.plot_date(final_dates, prices, '-o')
plt.xticks(rotation=90)
plt.xlabel('Date')
plt.ylabel('Price ($)')
plt.suptitle("Price of the %s stock in the last 3 months" % stock)
plt.show()
def Cleaning(writing_area1, writing_area2, writing_area3, writing_area4, writing_area5, writing_area6, writing_area7):
writing_area1.delete(0, END)
writing_area2.delete(0, END)
writing_area3.delete(0, END)
writing_area4.delete(0, END)
writing_area5.delete(0, END)
writing_area6.delete(0, END)
writing_area7.delete(0, END)
root.mainloop()
Спасибо!