LoginSignup
1
1

More than 5 years have passed since last update.

Python で Webスクレイピングして、結果をSlackする

Last updated at Posted at 2018-12-16

Python で Webスクレイピングして、結果をSlackする

with 初めてのPython。
プロパティcheck.ini から抽出した値とWebスクレイピングした値を
突合してSlackにメッセージ飛ばす。

ソース

# coding:utf-8

import json, os, requests
from bs4 import BeautifulSoup
import configparser

slack_token = '{SLACK_API_TOKENの値}'
#slack_token = os.getenv("SLACK_API_TOKEN")
#メンドいのでやらなかった

channelName = 'general'

def postSlackMsg( token, channelName, userName, msg ):
  # settings.
  URL='https://slack.com/api/chat.postMessage'

  # post
  post_json = {
    'token': token,
    'channel': channelName,
    'username': userName,
    'link_names': 1,
    'icon_emoji': ":robot:",
    'text': msg
  }
  requests.post( URL, data = post_json )

def post( url ):
  post_json = {  }
  response = requests.post( url, data = post_json )
  return json.dumps( response.text )

html = post( 'http://xxx.yyy.zzz.aaa/' )

soup = BeautifulSoup( html, "html.parser" )
tags = soup.findAll( '{スクレイピング条件}' )

# get properties.
config = configparser.ConfigParser()
config.read('check.ini')
dictMonitoring = dict( ( config.get( m, 'id' ), config.get( m, 'name' ) ) \
  for m in config.sections() )

reply = []
for tag in tags:
  if tag.string in dictMonitoring:
    # 条件に従って処理
    reply.append( tag.string + 'hoge' )

# post slack.
for msg in reply:
  postSlackMsg( slack_token, channelName, 'botName', msg )

読み込みプロパティファイル

check.ini
[member1]
id = A001
name = xxxx

[member2]
id = A002
name = yyyy

総括・感想

やればできるなって感じ。
BeautifulSoup と configparser の優秀さに驚いた。
numpyとか、AIなどで研究職に好まれるのも分かる気がした。
インデント言語と心の中で名付けた。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1