DEV Community

Shootacean
Shootacean

Posted on • Originally published at shootacean.com

1 1

指定したURLのHTTPステータスを一括でチェックするPythonスクリプト

Image from Gyazo

こんにちは。shootaceanです。

CSVファイルに定義したURLを元にGETリクエストを行い、レスポンスのHTTPステータスをチェックするPythonスクリプトです。

運営しているWEBサービスの検証をする際に利用しました。

pandasのインストール

$ pip3 install pandas
Enter fullscreen mode Exit fullscreen mode

Pythonスクリプト

host, csvFilePath, csvColumnName という変数を変更すれば、ご自身の環境に合わせることができると思います。

import urllib.request
import pandas as pd


host = "https://shootacean.com"
csvFilePath = "urls.csv"
csvColumnName = "uri"


def checkUrl(url):
    """指定したURLにGETリクエストした際のHTTPステータスをチェックする"""
    try:
        # GETリクエストをしてレスポンスを受け取る
        with urllib.request.urlopen(url) as response:
            # HTTPステータスが正常だった場合
            return True, response.code, url
    except urllib.error.HTTPError  as e:
        return False, e.code, url
    except urllib.error.URLError as e:
        if hasattr(e, 'reason'):
            return False, e.reason, url
        elif hasattr(e, 'code'):
            return False, e.code, url


if __name__ == "__main__":
    # CSVファイルを読み込む
    csv = pd.read_csv(csvFilePath)
    # CSVのレコード数分、チェックを繰り返す
    for uri in csv[csvColumnName]:
        url = host + uri
        # チェックを行う
        ok, code, url = checkUrl(url)
        if ok:
            # チェックが成功した場合
            print(code, url)
        else:
            # チェックが失敗場合
            print(code, url)

Enter fullscreen mode Exit fullscreen mode

CSVレイアウト例

使うのは1カラムだけなのでレイアウトは何でも大丈夫です。
1レコード目はヘッダーとして利用します。

uri
/
/contact
/privacy-policy
Enter fullscreen mode Exit fullscreen mode

参考

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay