Python でとある Web サイトにアクセスすると "HTTP Error 403: Forbidden" で怒られたが、User-Agent をセットすると成功(HTTP ステータスコード 200)した。
事象
- エラーメッセージ
$ python http_download.py HTTP Error 403: Forbidden
- コード(http_download.py)
#!/usr/bin/env python #-*- coding:utf-8 -*- import urllib.error import urllib.request def download_file(url, dst_path): request = urllib.request.Request(url) try: with urllib.request.urlopen(request) as web_file: data = web_file.read() with open(dst_path, mode='wb') as local_file: local_file.write(data) except urllib.error.URLError as e: print(e) url = '...' # URL を指定 dst_path = '...' # ファイルを保存するローカルパスを指定 download_file(url, dst_path)
原因
- User-Agent がセットされておらず、http サーバで拒否されている。
対策
- http ヘッダに User-Agent をセットする。
#!/usr/bin/env python #-*- coding:utf-8 -*- import urllib.error import urllib.request def download_file(url, dst_path): headers = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0" } # 追加 request = urllib.request.Request(url, headers=headers) # headers を追加 try: with urllib.request.urlopen(request) as web_file: data = web_file.read() with open(dst_path, mode='wb') as local_file: local_file.write(data) except urllib.error.URLError as e: print(e) url = '...' # URL を指定 dst_path = '...' # ファイルを保存するローカルパスを指定 download_file(url, dst_path)