# 抓取新聞內容

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

import requests
from bs4 import BeautifulSoup

# 全域變數
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):
   res = requests.get(url, headers=user_agent, timeout=30)
   if res.status_code == requests.codes.ok:
      # 以 BeautifulSoup 解析 HTML 程式碼
      soup = BeautifulSoup(res.text, 'html.parser')
      # 以 CSS 的 class 抓出各類頭條新聞
      p = soup.find('h1')
      print('標題：' + p.text)
      p = soup.find('time')
      print('時間：' + p.text)
      p = soup.find('div', class_='author-name C(#000) Fw(b) Maw(300px) Whs(nw) Ov(h) Tov(e)')
      print('作者：' + p.text)
      p = soup.find_all('p', class_='canvas-atom canvas-text Mb(1.0em) Mb(0)--sm Mt(0.8em)--sm')
      for s in p:
         print(s.text)

# 主程式 main
getNewsContent(yahooNewsUrl)
