import requests
from bs4 import BeautifulSoup
import pandas as pd
data = []
while True:
stock_symbol = input('\n請輸入要查詢(成交價)的股票代碼(離開=>quit): ')
if stock_symbol == 'quit':
break
url = 'https://tw.stock.yahoo.com/quote/' + stock_symbol
resp = requests.get(url)
if resp.status_code != 200:
print(f'{resp.status_code}錯誤,無法查詢!')
continue
soup = BeautifulSoup(resp.text, 'lxml')
price = soup.find(class_='D(f) Ai(fe) Mb(4px)').find('span').get_text()
print(price)
data.append((stock_symbol, price))
df = pd.DataFrame(data, columns=['Stock Symbol', 'Closing Price'])
df.to_excel('ClosingPrice.xlsx', index=False)