urllib2.Request检查URL是否可访问

时间:2014-07-25 09:43:04

标签: python urllib2

所以我有以下代码来验证某些url是否正确,我只需要200个响应,所以我使脚本工作正常,但它太慢了(:

import urllib2
import string
def my_range(start, end, step):
    while start <= end:
        yield start
        start += step
url = 'http://exemple.com/test/'
y = 1
for x in my_range(1, 5, 1):
 y =y+1 
 url+=str(y)
 print url 
 req = urllib2.Request(url)
 try:
    resp = urllib2.urlopen(req)
 except urllib2.URLError, e:
    if e.code == 404:
        print "404"
    else:
        print "not 404"
 else:
    print "200"
 url = 'http://exemple.com/test/'
body = resp.read()

在这个例子中,我假设我的本地主机中有以下目录,结果为

http://exemple.com/test/2
200
http://exemple.com/test/3
200
http://exemple.com/test/4
404
http://exemple.com/test/5
404
http://exemple.com/test/6
404

所以我搜索了如何更快地找到这段代码:

import urllib2
request = urllib2.Request('http://www.google.com/')
response = urllib2.urlopen(request)
if response.getcode() == 200:
   print "200"    

它似乎更快但是当我用404(http://www.google.com/111)测试它时 它给了我这个结果:

Traceback (most recent call last):
  File "C:\Python27\res.py", line 3, in <module>
    response = urllib2.urlopen(request)
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found

任何想法的家伙? 非常感谢任何帮助:)

1 个答案:

答案 0 :(得分:1)

HTTPError被定义为一系列例外,因此您可以在以下情况下使用Try / Except:

import urllib2
request = urllib2.Request('http://www.google.com/')
try:
    response = urllib.urlopen(request)
    # do stuff..
except urllib2.HTTPError: # 404, 500, etc..
    pass

您还可以为except添加另一个urllib2.URLError子句,其中包含其他(非HTTP)错误,例如超时。