import requests
from bs4 import BeautifulSoup
import openpyxl

ClosingPrice = {}

while True:

    print()
    user = input('請輸入要查詢(成交價)的股票代碼(離開=>quit): ')

    url = 'https://tw.stock.yahoo.com/quote/'+user  

    if user == 'quit':
        break

    else:
        response = requests.get(url)
        
        if response.status_code != 200:
            print(f'{response.status_code}錯誤,無法查詢!')
        else:
            html_doc = response.text
            soup = BeautifulSoup(html_doc, 'lxml')
            
            price = soup.find(class_='D(f) Ai(fe) Mb(4px)').find('span').get_text()

            print(price)
                 
            ClosingPrice[user] = price
        
workbook = openpyxl.Workbook()

sheet = workbook.active
            
for row_idx, (key, value) in enumerate(ClosingPrice.items(), start=1):
    sheet.cell(row = row_idx, column = 1, value = key)
    sheet.cell(row = row_idx, column = 2, value = value)

workbook.save('ClosingPrice.xlsx')