LoginSignup
6
5

More than 3 years have passed since last update.

Python で HTTP リダイレクト先の URL を取得する

Last updated at Posted at 2020-08-07

概要

  • Python 3 で HTTP リダイレクト先の URL を取得する
  • 動作確認環境: Python 3.8.5 + macOS Catalina

ソースコード

get_redirect.py というファイル名で以下の内容を保存する。

get_redirect.py
import sys
import urllib.request

# リダイレクトしないハンドラークラス
class NoRedirectHandler(urllib.request.HTTPRedirectHandler):
  # HTTPRedirectHandler.redirect_request をオーバーライド
  def redirect_request(self, req, fp, code, msg, hdrs, newurl):
    self.newurl = newurl # リダイレクト先URLを保持
    return None

# リダイレクト先 URL を取得する関数
def get_redirect_url(src_url):
  # リダイレクトしないハンドラーをセット
  no_redirect_handler = NoRedirectHandler()
  opener = urllib.request.build_opener(no_redirect_handler)
  try:
    with opener.open(src_url) as res:
      return None # リダイレクトしない URL だった
  except urllib.error.HTTPError as e:
    if hasattr(no_redirect_handler, "newurl"):
      return no_redirect_handler.newurl # リダイレクト先 URL を返す
    else:
      raise e # リダイレクト以外で発生した例外なので投げ直す

# コマンドライン引数を取得
src_url = sys.argv[1]

# リダイレクト先URLを取得
redirect_url = get_redirect_url(src_url)

# リダイレクト先URLを出力
if redirect_url is not None:
  print(redirect_url)

実行例。

$ python get_redirect.py https://bit.ly/3kmTOkc
https://t.co/yITSBp4ino
$ python get_redirect.py https://t.co/yITSBp4ino
https://qiita.com/niwasawa
$ python get_redirect.py https://qiita.com/niwasawa

簡略版

get_redirect.py というファイル名で以下の内容を保存する。

get_redirect.py
import sys
import urllib.request

# リダイレクト先URLを取得する関数
def get_redirect_url(src_url):
  with urllib.request.urlopen(src_url) as res:
    url = res.geturl() # 最終的な URL を取得
    if src_url == url:
      return None # 指定された URL と同じなのでリダイレクトしていない
    else:
      return url # 指定された URL と異なるのでリダイレクトしている

# コマンドライン引数を取得
src_url = sys.argv[1]

# リダイレクト先URLを取得
redirect_url = get_redirect_url(src_url)

# リダイレクト先URLを出力
if redirect_url is not None:
  print(redirect_url)

実行例。
簡易版では、リダイレクト先の URL にリクエストを投げてしまったり、多段リダイレクトの場合は最終的な URL を出力する。

$ python get_redirect.py https://bit.ly/3kmTOkc
https://qiita.com/niwasawa
$ python get_redirect.py https://t.co/yITSBp4ino
https://qiita.com/niwasawa
$ python get_redirect.py https://qiita.com/niwasawa

参考資料

6
5
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
6
5