import requests
from bs4 import BeautifulSoup
ClosingPrice = {}
while True:
print()
user = input('請輸入要查詢(成交價)的股票代碼(離開=>quit): ')
url = 'https://tw.stock.yahoo.com/quote/'+user
if user == 'quit':
break
else:
try:
response = requests.get(url)
html_doc = response.text
soup = BeautifulSoup(html_doc, 'lxml')
price = soup.find('span', class_='Fz(32px) Fw(b) Lh(1) Mend(16px) D(f) Ai(c) C($c-trend-up)').text
print(f'{user}的成交價:{price}')
ClosingPrice[user] = price
except AttributeError:
print('查無該代碼')
continue
file = open('ClosingPrice.csv', 'w', encoding = 'utf-8')
for price in ClosingPrice:
file.write(f'\t{price},{ClosingPrice[price]}\n')
file.close()