检查网址链接是否正确
我想打开很多网址(我打开一个网址,搜索这个网站上的所有链接,然后也打开这些链接,或者从这些链接下载图片等等)。所以我首先想检查一下网址是否正确,于是我用了一个if
语句:
if not urlparse.urlparse(link).netloc:
return 'broken url'
但是我发现有些网址没有通过这个检查。我遇到一个网站,它的链接看起来像这样://b.thumbs.redditmedia.com/7pTYj4rOii6CkkEC.jpg
,但是我却遇到了一个错误:
ValueError: unknown url type: //b.thumbs.redditmedia.com/7pTYj4rOii6CkkEC.jpg
,而我的if
语句并没有捕捉到这个问题。那我该怎么更准确地检查一个网址是否有效呢?
2 个回答
0
如果你没有明确说明使用的是哪个库,你可以这样做:
import urllib2
import re
def is_fully_alive(url, live_check = False):
try:
if not urllib2.urlparse.urlparse(url).netloc:
return False
website = urllib2.urlopen(url)
html = website.read()
if website.code != 200 :
return False
# Get all the links
for link in re.findall('"((http|ftp)s?://.*?)"', html):
url = link[0]
if not urllib2.urlparse.urlparse(url).netloc:
return False
if live_check:
website = urllib2.urlopen(url)
if website.code != 200:
print "Failed link : ", url
return False
except Exception, e:
print "Errored while attempting to validate link : ", url
print e
return False
return True
检查你的网址:
>>> is_fully_alive("http://www.google.com")
True
逐个打开每一个链接来检查:
# Takes some time depending on your net speed and no. of links in the page
>>> is_fully_alive("http://www.google.com", True)
True
检查一个无效的网址:
>>> is_fully_alive("//www.google.com")
Errored while attempting to validate link : //www.google.com
unknown url type: //www.google.com
False
1
这很简单:
import urllib2 def valid_url(url): try: urllib2.urlopen(url) return True except Exception, e: return False print valid_url('//b.thumbs.redditmedia.com/7pTYj4rOii6CkkEC.jpg') # False print valid_url('http://stackoverflow.com/questions/25069947/check-if-the-url-link-is-correct') # True
你也可以通过下面的方式读取整个文档:
urllib2.urlopen(url).read()
一般来说,如果你想从一个HTML文档中下载所有的图片,可以这样做:
for link, img in re.findall('http.?:\/\/b\.thumbs\.redditmedia\.com\/(\w+?\.(?:jpg|png|gif))', load(url)): if not os.path.exists(img): with open(img, 'w') as f: f.write(link)