LoginSignup
0
0

More than 1 year has passed since last update.

指定したURLのリンクが有効かどうかをチェックするpythonスクリプトを作成2

Last updated at Posted at 2021-01-10

以下の更新版

指定したURLのリンクが有効かどうかをチェックするpythonスクリプトを作成

以下のgithub actionsのファイルも参考になる

https://github.com/paramt/url-checker
check_links.py

コード

こちらにあるものと同じ

チェック対象のURLリスト作成

カレントディレクトリ以下のhttps://...と続く文字列をなるべくgrepする。input.txtという名前で保存。

grep -r "https://" * > test.txt
cat test.txt | sed -e 's/.*https//' | sed "s/^/http/g"  > test.txt
cat test2.txt | sed 's/>//g' | sed 's/"//g' | sed 's/)//g' | sed 's/;//g' | sed 's/]//g' | cut -d' ' -f 1 > input.txt 

チェック

input.txtのURLにアクセスできるかどうかを確認する。

$ python3 check_url.py

# 出力結果
#     アクセスできる→OK
#     アクセスできない→NotFound
#     ※ ただし、grep結果が意図通りでない場合もあるので確認する。

NotFound:http://www.kernel.org/pub/linux/kernel/v5.x/linux-${PV}.tar.xz
OK:http://facebook.github.io/watchman/
...
check_url.py
#-*- using:utf-8 -*-
import urllib.request, urllib.error

with open('out.txt', 'w') as txt:
    txt.write("chdck result\n")

def checkURL(url):
    try:
        f = urllib.request.urlopen(url)
        f.close()
        return True
    except:
        return False

if __name__ == '__main__':

    with open("./input.txt") as f:
        for url in f:
            # print(url, end='')
            ret = checkURL(url)
            if ret == True:
                result = "OK:"
            else:
                result = "NotFound:"

            ret_text = result + url
            #ret_text = ret_text.replace('\n', '')
            print(ret_text)
            if ret != True:
                with open('out.txt', 'a') as txt:
                    txt.write(ret_text)

結果

結果OK/NGを以下に出力する

cat out.txt

参考

指定したURLのリンクが有効かどうかをチェックするpythonスクリプトを作成
入力した文字列から、指定した文字列より右の文字列をとりだす

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