我有一个 URL 列表(1000 多个),这些 URL 已经存储了一年多了。我想遍历并验证它们,看看它们是否仍然存在。检查所有内容并返回不返回网站的列表的最佳/最快方法是什么?
最佳答案
这有点慢,但你可以使用类似这样的东西来检查 url 是否有效
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 checkout(如果网站不存在不太方便检查):
import socket
try:
socket.gethostbyname('www.google.com')
except socket.gaierror as ex:
print "not existe"
关于Python验证url转到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4041443/