# 奇摩股市

#coding=UTF-8
#!/usr/bin/python

import requests
from bs4 import BeautifulSoup

# 全域變數
yahooStockUrl = 'https://tw.stock.yahoo.com/q/q?s='
user_agent = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}

def myCut(s):
   tbl = [
      '加到',
      '\n',
   ]

   for t in tbl:
      n = s.find(t)
      if n >= 0:
         s = s[:n]
   return s

def getStockContent(url):
   res = requests.get(url, headers=user_agent, timeout=30)
   if res.status_code == requests.codes.ok:
      soup = BeautifulSoup(res.text, 'html.parser')
      t = soup.find('table', attrs={'border' : '2'})
#      print(t.text)
#      print(t)
      th = t.find_all('th')
      td = t.find_all('td')
      for i in range(len(th)-1):
         s = td[i].text
         if i == 0 or i == 5:
            s = myCut(s)
#         print(th[i].text + '  ' + td[i].text)
         print(th[i].text + '  ' + s)

# 主程式 main
stockId = input('請輸入股票代號: ')
getStockContent(yahooStockUrl + stockId)

input('Press enter to continue......')
