Python 验证 URL 是否有效
我有一份包含1000多个网址的列表,这些网址已经存放了一年多了。我想逐个检查这些网址,看看它们是否还存在。有没有什么好的方法或者最快的方式来检查这些网址,并返回那些无法访问的网站的列表呢?
2 个回答
0
看看这个:
最后:
import ping, socket
try:
result = ping.do_one('http://stackoverflow.com/', timeout=2)
except socket.error, e:
# url cannot be reached
print "Error:", e
11
这个方法有点慢,但你可以用这样的方式来检查一个网址是否在线。
import urllib2
try:
urllib2.urlopen(url)
return True # URL Exist
except ValueError, ex:
return False # URL not well formatted
except urllib2.URLError, ex:
return False # URL don't seem to be alive
比起urllib2,使用 httplib 会更快一些。
import httplib
try:
a = httplib.HTTPConnection('google.com')
a.connect()
except httplib.HTTPException as ex:
print "not connected"
你也可以进行DNS检查(不过这不是很方便,因为它不能很好地判断一个网站是否不存在):
import socket
try:
socket.gethostbyname('www.google.com')
except socket.gaierror as ex:
print "not existe"