0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

MattermostにWebページのテーブルをそのまま転記させるスクリプト

Posted at

Webページにくる通知を読んでくれない人に向けて強制的に情報発信するためのものとしてChatGPTに考えてもらいました。
イメージはRedmineのチケット一覧です。

質問

アクセス先のページにあるテーブルを、Mattermostの書式に変換するスクリプトを作ってほしいです。
・テーブルは"listing tickets"というclassで以下の構成をしている
 ticketNO,概要,ステータス,分類,優先度,発行者,回答期限,完了期限
・ticketNOは数字が入り、Mattermostに投稿する際には以下のようにURLを生成し、リンクを張ってほしい
 https://localhost/ticketNO
・beautifulsoupを使って解析する
・ライブラリのインストールに関する説明は省略し、スクリプトのみを表示すること

回答

以下は、指定された条件に基づいてWebページからテーブルを抽出し、Mattermostの書式に変換するPythonスクリプトです。このスクリプトは、beautifulsoup4ライブラリを使用しています。

import requests
from bs4 import BeautifulSoup

def extract_table(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    table = soup.find('table', {'class': 'listing tickets'})

    if table:
        headers = []
        rows = table.find_all('tr')
        for header in rows[0].find_all('th'):
            headers.append(header.text)

        data = []
        for row in rows[1:]:
            cells = row.find_all('td')
            rowData = {}
            for i, cell in enumerate(cells):
                rowData[headers[i]] = cell.text
            data.append(rowData)

        return data
    else:
        return None

def to_mattermost_format(data):
    formatted_data = []
    for row in data:
        ticketNO = row['ticketNO']
        url = f"https://localhost/{ticketNO}"
        formatted_row = f"[{ticketNO}]({url}) | {row['概要']} | {row['ステータス']} | {row['分類']} | {row['優先度']} | {row['発行G']} | {row['回答期限']} | {row['完了期限']}"
        formatted_data.append(formatted_row)

    return "```\n" + " | ".join(['ticketNO', '概要', 'ステータス', '分類', '優先度', '発行者', '回答期限', '完了期限']) + "\n" + "\n".join(formatted_data) + "\n```"

url = "https://example.com/path/to/table"  # ここに対象のURLを入力してください
table_data = extract_table(url)
if table_data:
    mattermost_formatted_data = to_mattermost_format(table_data)
    print(mattermost_formatted_data)
else:
    print("テーブルが見つかりませんでした")

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?