2016-06-12 7 views
0

3XXを含むhttpステータスコードを取得しようとしていますが、コードから印刷できません。ここでPython 3(urllib)でHTTPステータスコードを出力するには

はコードです:

import urllib 
import urllib.request 
import urllib.error 

urls = ['http://hotdot.pro/en/404/', 'http://www.google.com', 'http://www.yandex.ru', 'http://www.python.org', 'http://www.voidspace.org.uk'] 
fh = open("example.txt", "a") 
def getUrl(urls): 
    for url in urls: 
     try: 
      with urllib.request.urlopen(url) as response: 
       requrl = url 
       the_page = response.code 
       fh.write("%d, %s\n" % (int(the_page), str(requrl))) 
     except (urllib.error.HTTPError, urllib.error.URLError) as e: 
      requrl = url 
      print (e.code) 
      fh.write("%d, %s\n" % (int(e.code), str(requrl))) 
getUrl(urls) 

誰かがこれで私を助けることができますか?

+0

はあなたの本当の質問です:リダイレクトを無効にする方法? (つまり、 'urlopen()'は自動的に30xのリダイレクトに従わないでしょうか?) – jfs

+0

はい、私はURLをリダイレクトしたくありません。応答時間とともに応答コードを印刷するだけです。 – arjun9916

+0

参照[PythonでURLを要求し、リダイレクトに従わない簡単な方法はありますか?](http://stackoverflow.com/q/110498/4279) – jfs

答えて

3

クラスURLErrorのすべてのエラーがcodeになるわけではありません。一部にはreasonしか含まれません。

また、は同じexceptブロックにURLErrorHTTPErrorをキャッチすることは良いアイデアではありません(docsを参照してください):

def getUrl(urls): 
    for url in urls: 
     try: 
      with urllib.request.urlopen(url) as response: 
       requrl = url 
       the_page = response.code 
       print(the_page) 
       fh.write("%d, %s\n" % (int(the_page), str(requrl))) 
     except urllib.error.HTTPError as e: 
      requrl = url 
      print(e.code) 
      fh.write("%d, %s\n" % (int(e.code), str(requrl))) 
     except urllib.error.URLError as e: 
      if hasattr(e, 'reason'): 
       print(e.reason) 
       fh.write("%s, %s\n" % (e.reason, str(requrl))) 
      elif hasattr(e, 'code'): 
       print(e.code) 
       fh.write("%d, %s\n" % (int(e.code), str(requrl))) 
+0

私はまだこれで3XXのhttp応答を取得できません。 。 – arjun9916

関連する問題