#!/usr/bin/env python3.63
import sys
import io
import datetime
import MySQLdb
import feedparser
from datetime import datetime
#import sqlite3
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
html = """Content-type: text/html\n
<!DOCTYPE html>
<html lang=\"ja\">\n
<link rel = \"stylesheet\" href = \"style.css\">""" + \
"""<head>\n
<meta charset=\"UTF-8\">\n
<title>Document</title>\n
</head><body>\n
<h1><a href=\"https://www.codingstock.jp/centos7-python-cgi-rss\">
<img src=\"https://www.codingstock.jp/wp-content/uploads/tcd-w/logo.jpg?1569061779\"></a></h1>"""
print(html)
connection = MySQLdb.connect(
host='localhost', user='dbuser', passwd='Karokakku1190#', db='yahooNews', charset='utf8')
cursor = connection.cursor()
# エラー処理(例外処理)
try:
# table dailyportalが存在していると削除 今回はコメントアウト
# cursor.execute("drop table if exists `dailyportal`;")
# table topicが存在しないとテーブル作成します。
# cursor.execute("drop table if exists `dailyportal`;")
sql = '''create table if not exists dailyportal (
title varchar(256) PRIMARY KEY NOT NULL,
link varchar(128),
published datetime,
topicUpDate datetime);'''
cursor.execute( sql )
#RSS取得し feedparser でパース
ynews = feedparser.parse('https://dailyportalz.jp/feed/headline')
print( "<div class=\"wrapper\">")
# -----------------------------------------------
replace_into = "replace into dailyportal (title,link,published,topicUpDate) values (%s, %s, %s, %s);"
# replace into は キーに対応データが存在すれば UPDATE, 存在しなければ INCERT として機能します。
# mysql の方言 ? とりあえず mysqlのみがサポートしているようです。
for entry in ynews.entries:
timestamp_str1 = entry.published
dt = datetime.strptime(timestamp_str1,'%a, %d %b %Y %H:%M:%S %z')
news = [
(entry.title,
entry.link,
str(dt)[:19],
datetime.now().strftime("%Y/%m/%d %H:%M:%S"))
]
cursor.executemany(replace_into,news)
print("</div>")
except MySQLdb.Error as e:
print('</div>MySQLdb.Error: ', e )
connection.commit() # 一括書き込みの実態。実際のデータベースの書き込みはこのコマンドで実行されます。
connection.close()