Memoize2

Python HTTP_Status_code を取得する


#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError

def get_http_status_code(url) :
    req = Request(url)
    try :
        response = urlopen(req)
        return response.code
    except HTTPError as e :
        # except HTTPError が 必ず 最初に来る必要がある。そうしないと except URLError も HTTPError を捕捉してしまう。
        return e.code
    except URLError as e :
        return e.reason
    else :
        return None

if __name__ == '__main__' :
    for url in ('http://basicwerk.com', 'http://basicwerk.com/unknown/') :
        print("{} : HTTP_STATUS is {}".format(url, get_http_status_code(url)))
        # ->
        # http://basicwerk.com : HTTP_STATUS is 200
        # http://basicwerk.com/unknown/ : HTTP_STATUS is 404

参考: urllib パッケージを使ってインターネット上のリソースを取得するには > エラーをラップする

 

Last modified: 2016-12-19

Page Top

Index

Bw

Author: 中村 心 Shin Nakamura, Email: sn(at)i.basicwerk.com


© Shin Nakamura/BasicWerk 2008 - 2024