# 新聞內容寫入檔案

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

import requests
from bs4 import BeautifulSoup
import os

# 全域變數
yahooNewsUrl = 'https://tw.news.yahoo.com/lifestyle/%E6%B0%B8%E9%BD%A1%E5%9F%BA%E9%87%91%E6%9C%83%E6%8E%A8-%E6%8A%8A-%E8%A6%96%E9%9A%9C%E8%80%85%E9%9F%B3%E6%A8%82%E7%99%BC%E5%B1%95%E4%B8%AD%E5%BF%83%E6%98%8E%E5%B9%B4%E6%88%90%E7%AB%8B-080500517.html'
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 getNewsContent(url):
   dir = os.path.dirname(__file__)  # 取得目前執行目錄
   fn = os.path.join(dir, 't.txt')
   f = open(fn, 'w', encoding='utf-8')  # 開啟寫入檔案格式 utf8

   res = requests.get(url, headers=user_agent, timeout=30)
   if res.status_code == requests.codes.ok:
      soup = BeautifulSoup(res.text, 'html.parser')
      p = soup.find('h1')
      if p != None and p.text != None:
         f.write(p.text + '\n')
      p = soup.find('time')
      if p != None and p.text != None:
         f.write(p.text + '\n')
      p = soup.find('div', class_='author-name C(#000) Fw(b) Maw(300px) Whs(nw) Ov(h) Tov(e)')
      if p != None and p.text != None:
         f.write(p.text + '\n')
      p = soup.find_all('p', class_='canvas-atom canvas-text Mb(1.0em) Mb(0)--sm Mt(0.8em)--sm')
      for s in p:
         if s.get('content') == s.text:
            if s != None and s.text != None:
               f.write(s.text + '\n')
   f.close()

# 主程式 main
getNewsContent(yahooNewsUrl)
