遭遇例

Python

カテゴリー: エラー  閲覧数:257 配信日:2017-05-26 12:57


修正前


▼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 パッケージを使ってインターネット上のリソースを取得するには