我在 python 中编写了一个简单的 url 验证器和缩短器,如何从网站 url 保存小尺寸的图像?并认识到它不是像 .rar 或 .zip 这样的“文件”?如果您编辑我的代码以获得更好的性能,我很感激..
from urllib2 import Request, urlopen, URLError
from urlparse import urlparse
import string
import random
url = raw_input('plZ enter the url: ').lower() #get input and convert to lowercase
while True:
if url[0:7] == 'http://' or url[0:8] == 'https://' or url[0:6] =='ftp://': #check the url protocol
try: #try to open url
response = urlopen(url)
parsed_url = urlparse(url)
rand_url = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in range(6))
print " The shortened url is: http://url.com/" + rand_url
print "\n Original URL is: "+url
exit()
except URLError, e: #except the error by asking the address again
if hasattr(e, 'reason'):
print "URL is not valid or server is NOT responsive..plZ try again.."
url = raw_input('plZ enter the url: ').lower()
#print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.' #message in case of server or connection error
print 'Error code: ', e.code
else:
print "\n protocol missing, using HTTP instead.. \n"
url = "http://"+url