import requests
from bs4 import BeautifulSoup
import os
import codecs
import copy

tseUrl = 'https://tw.stock.yahoo.com/d/i/rank.php?t=vol&e=tse'  # 上市買超排行
otcUrl = 'https://tw.stock.yahoo.com/d/i/rank.php?t=vol&e=otc'  # 上櫃買超排行

class Money:
   __fp = None

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

   def printTitle(self, t):
      global __fp
      i = t.find(' - ')
      if i >= 0:
         __fp.write(t[:i] + '\r\n')

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

   def getTd(self, tr):
      global __fp
      td = tr.find_all('td')
      i = 0
      str = None
      for s in td:
         i = i + 1
         if i == 1 or i >= 10:
            continue
         if i == 2:
#            if s.text[0:2] == '00':
#               return None
            str = copy.copy(s.text)
         __fp.write(s.text + ' ')
      __fp.write('\r\n')
      return str

   def buySale(self, stockId):
      global __fp
      url = 'https://goodinfo.tw/StockInfo/StockDetail.asp?STOCK_ID=' + stockId
      # 模擬瀏覽器
      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'}
      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 程式碼
#         self.printTitle(soup.find('title').text)
         t = soup.find_all('table', {'class' : 'solid_1_padding_4_0_tbl', 'bgcolor' : '#d7e6f4'})
         n = 0
         for s in t:
            n = n + 1
            if n == 2:
               tr = s.find('tr', bgcolor='#d7e6f4')
               a = tr.find('a')
#               __fp.write(a.text + '\r\n')
            elif n == 3:
               tr = s.find_all('tr', bgcolor='white')
               for t2 in tr:
                  self.printBuySale(t2)
         __fp.write('\r\n')

   def buySale2(self, stockId):
      global __fp
      url = 'https://goodinfo.tw/StockInfo/StockDetail.asp?STOCK_ID=' + stockId
      # 模擬瀏覽器
      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'}
      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 程式碼
#         self.printTitle(soup.find('title').text)
         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)
         __fp.write('\r\n')

   def myStock(self):
      tbl = {
         '2504',
         '6153',
         '2449',
      }

      for s in tbl:
         self.buySale2(s)

   def hotStock(self, url, num):
      global __fp
      # 模擬瀏覽器
      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'}
      res = requests.get(url, headers=user_agent, timeout=30)  # 下載網頁內容
      if res.status_code == requests.codes.ok:  # 確認是否下載成功
         # res.encoding = 'utf-8'
         soup = BeautifulSoup(res.text, 'html.parser')  # 以 BeautifulSoup 解析 HTML 程式碼
         t = soup.find('table', {'cellpadding' : '3', 'cellspacing' : '1'})
#         a = t.find_all('a')
         tr = t.find_all('tr', bgcolor='#ffffff')
         n = 0
         for s in tr:
#         for s in a:
            str = self.getTd(s)
#            if str == None or str[0:2] == '00':
#               continue
            i = str.find(' ')
#            self.buySale(str[:i])
            self.buySale2(str[:i])
            n = n + 1
            if n >= num:
               break

if __name__ == "__main__":
   money = Money()
   money.myStock()
   money.hotStock(tseUrl, 30)
   money.hotStock(otcUrl, 5)

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