Skip to content

Instantly share code, notes, and snippets.

@af12066
Created April 23, 2016 09:33
Show Gist options
  • Save af12066/a9b6614b699de524e8016f7af17838bc to your computer and use it in GitHub Desktop.
Save af12066/a9b6614b699de524e8016f7af17838bc to your computer and use it in GitHub Desktop.
import urllib.request
import re
import urllib.parse
import codecs
import filecmp
import os.path
import os
from bs4 import BeautifulSoup
from slacker import Slacker
from datetime import datetime
class Slack(object):
__slacker = None
def __init__(self, token):
self.__slacker = Slacker(token)
def post_message_to_channel(self, channel, message):
"""
Slackチームの任意のチャンネルにメッセージを投稿する。
"""
channel_name = "#" + channel
self.__slacker.chat.post_message(channel_name, message)
def writeFile(fileName, content):
"""
ファイル書き出し
"""
print(fileName)
f = codecs.open(fileName, 'w', 'utf-8')
f.write(content)
f.close()
if __name__ == '__main__':
slack = Slack('...') #Slackのトークンを入れる
#今月と翌月のデータを取得
uri = 'http://www.example.com/cancelCalendar/t04/calendar{0:d}{1:02d}-{2:02d}.html'.format(datetime.today().year, datetime.today().month, (lambda x: x if x != 12 else x - 11)(datetime.today().month + 1))
html = urllib.request.urlopen(uri)
soup = BeautifulSoup(html, 'lxml')
link = soup.find_all('a', href=re.compile("/cancel/")) #href属性に'/cancel/'を含むa要素を取得し,相対パスを絶対パスに変換
for a in link:
path = urllib.parse.urljoin(uri, a['href']) #href属性のみを取得
print(path)
fileName = path.split('/')[-1]
fileName = fileName.replace("html", "txt")
html2 = urllib.request.urlopen(path) #リストの要素のURLをオープン
soup2 = BeautifulSoup(html2, 'lxml')
dat = soup2.find_all(text=True) #テキストをすべて取得
settext = "\n".join([x for x in dat if x != '\n']) #改行文字のみのリスト項目を削除.リストを結合し,文字列を整形
# スクレイピングしたテキストを書き出す.
# もしその日付のファイルが存在しなければ新規に作成し,
# 既にファイルが存在していれば拡張子に'.tmp'を付加して一時ファイルを作成する.
# もとのtxtファイルとtmpファイルの差分を比較し,更新があればtxtファイルを更新し,Slackにポストする.
if os.path.isfile(fileName):
tmpfileName = fileName + '.tmp'
writeFile(tmpfileName, settext)
if filecmp.cmp(fileName, tmpfileName):
print("no diff")
else:
writeFile(fileName, settext)
slack.post_message_to_channel("class", settext) #Slackにポスト (チャンネル, テキスト)
os.remove(tmpfileName)
else:
#print('write a new file')
slack.post_message_to_channel("class", settext) #Slackにポスト (チャンネル, テキスト)
writeFile(fileName, settext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment