2017-05-29 8 views
0

urllib.requestパッケージを使用して、Webページを開いたり、読み込んだりしています。私のコードがリダイレクトをうまく処理することを確認したいと思います。今私はリダイレクト(HTTPError)を見ると失敗します。誰かがそれをどう扱うかについて私を導くことができますか?私のコードは現在次のようになっています:リダイレクトハンドラpython 3.4.3

try: 
     text = str(urllib.request.urlopen(url, timeout=10).read()) 
except ValueError as error: 
     print(error) 
except urllib.error.HTTPError as error: 
     print(error) 
except urllib.error.URLError as error: 
     print(error) 
except timeout as error: 
     print(error) 

私はこんなことを助けてください。ありがとう!

+0

はあなたがそこにいたときに見たい行動を説明リダイレクト。 –

+0

私は代わりに失敗したい、リダイレクトされたページに行き、そのウェブページを読む。特に、httpからhttpsへのリダイレクトは同じページに行われます。 – anon

答えて

0

requestsパッケージを使用すると、より良い解決策を見つけることができました。あなたが処理する必要が唯一の例外である:

try: 
     r = requests.get(url, timeout =5) 

except requests.exceptions.Timeout: 
# Maybe set up for a retry, or continue in a retry loop 

except requests.exceptions.TooManyRedirects as error: 
# Tell the user their URL was bad and try a different one 

except requests.exceptions.ConnectionError: 
# Connection could not be completed 

except requests.exceptions.RequestException as e: 
# catastrophic error. bail. 

そして、そのページのテキストを取得するために、すべてを行う必要がある: r.text

0

私はリダイレクトをキャッチするために、特別なURLopenerを使用します。

import urllib 

class RedirectException(Exception): 
    def __init__(self, errcode, newurl): 
     Exception.__init__(self) 
     self.errcode = errcode 
     self.newurl = newurl 

class MyURLopener(urllib.URLopener): 
    # Error 301 -- relocated (permanently) 
    def http_error_301(self, url, fp, errcode, errmsg, headers, data=None): 
     if headers.has_key('location'): 
      newurl = headers['location'] 
     elif headers.has_key('uri'): 
      newurl = headers['uri'] 
     else: 
      newurl = "Nowhere" 
     raise RedirectException(errcode, newurl) 

    # Error 302 -- relocated (temporarily) 
    http_error_302 = http_error_301 
    # Error 303 -- relocated (see other) 
    http_error_303 = http_error_301 
    # Error 307 -- relocated (temporarily) 
    http_error_307 = http_error_301 

urllib._urlopener = MyURLopener() 

は今、私はRedirectExceptionと出来上がりをキャッチする必要がある - 私は、リダイレクトがあった知っていると私は、URLを知っています。警告 - 私はPython 2.7でコードを使用していますが、Python 3で動作するかどうかわかりません。

+0

これはPython 3ではうまくいかないようです... – anon

関連する問題