在Python 3(urllib)中打印http状态代码

2024-05-15 13:11:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取包括3XX在内的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)

有人能帮我吗?


Tags: 代码orgimporthttpurlrequestaswww