エラーメッセージ
状態:-
閲覧数:632
投稿日:2017-05-26
更新日:2017-05-26
[error] [client 123.456.78.910] urllib.error.HTTPError: HTTP Error 403: Forbidden
原因
ユーザエージェントの問題
・ユーザエージェントを付与せず、Webサイトへアクセスしたため
対策
ユーザエージェントを偽装して、Webサイトへアクセス
遭遇例
修正前
▼index.py
import urllib.parse
import urllib.request
from bottle import route
@route('/')
def index():
url = 'https://gihyo.jp/dp'
req = urllib.request.Request(url)
with urllib.request.urlopen(req) as response:
the_page = response.read()
return(the_page)
修正後
Firefoxに偽装してアクセス
▼index.py
import urllib.parse
import urllib.request
from bottle import route, view
@route('/')
def index():
url = 'https://gihyo.jp/dp'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
headers = {'User-Agent': user_agent}
req = urllib.request.Request(url,headers=headers)
with urllib.request.urlopen(req) as response:
the_page = response.read()
return(the_page)
・urllib パッケージを使ってインターネット上のリソースを取得するには