# -*- coding:UTF-8 -*-
#!/usr/bin/python

import requests
from bs4 import BeautifulSoup
import codecs
import os

# 全域變數
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'}

class Stock:
   def __init__(self, filename='stock.txt'):
      print('Test Stock')
      dir = os.path.dirname(__file__)  # 取得目前路徑
      fn = os.path.join(dir, filename)
      self.__fp = codecs.open(fn, 'w', 'utf-8')
      
   def terminate(self):
      self.__fp.close()
      self.__fp = None

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

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

   def getNow(self, stockId):
      try:
         url = 'https://tw.stock.yahoo.com/q/q?s=' + stockId
         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'})
#            upDate = soup.find('font', class_='tt').text[7:]
#            self.__fp.write('日期: ' + upDate + '\r\n')
            th = t.find_all('th')
            td = t.find_all('td')
            for i in range(len(td)-1):
               s = td[i].text
               if i == 0 or i == 5:
                  s = self.myCut(s)
               self.__fp.write(th[i].text + ': ' + s + '\r\n')
      except AttributeError:
         print('找不到相關資料，或網路連線發生問題！')

   def printBuySale(self, tr):
      td = tr.find_all('td')
      s = ''
      for t in td:
         if len(t.text) == 0:
            continue
         s = s + t.text + ' '
      s = s.replace('→', ' 轉 ')
      self.__fp.write(s + '\r\n')

   def getBuySale(self, stockId):
      url = 'https://goodinfo.tw/StockInfo/StockDetail.asp?STOCK_ID=' + stockId
      res = requests.get(url, headers=user_agent, timeout=30)  # 下載網頁內容
      if res.status_code == requests.codes.ok:  # 確認是否下載成功
         res.encoding = 'utf8'
         soup = BeautifulSoup(res.text, 'html.parser')  # 以 BeautifulSoup 解析 HTML 程式碼
         t = soup.find('nobr', style='font-size:9pt;color:gray;')
         self.__fp.write(t.text + '\r\n')
         t = soup.find('a', style='font-size:14pt;font-weight:bold;')
         self.__fp.write(t.text + '\r\n')
         t = soup.find_all('table', {'class' : 'solid_1_padding_4_4_tbl', 'bgcolor' : '#d7e6f4'})
         for s in t:
            if s.text.find('買進(張)') < 0:
               continue
            tr = s.find_all('tr', bgcolor='white')
            for t2 in tr:
               self.printBuySale(t2)
         self.__fp.write('\r\n')

if __name__ == "__main__":
   stock = Stock('t.txt')
   stock.getNow('2368')
   stock.getBuySale('2368')

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