2012-08-16 105 views
0

我写了一个简单的URL验证和缩写在python中,我怎么能从网站的url保存图像的小尺寸?并认识到它不是像.rar或.zip这样的“文件”?我apreciate如果编辑我的代码有更好的表现..在python中的URL验证和缩短

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 
+0

你想想图标或者说整个页面的图像,因为它是由歌剧院,Firefox或Chrome表明,他们显示了“快速拨号”? – 2012-08-16 12:19:42

+0

恰好像歌剧和火狐的形象。 – 2012-08-16 12:25:44

+0

不要使用'lower()'。网址是区分大小写的,原则上通常在实践中。 – alexis 2012-08-16 20:49:05

回答

2

1)如果你正在寻找抓取和图像,并调整其大小,考虑使用或者PIL或PyImageMagik [Python绑定的出色ImageMagik]

2)如果你正在寻找抓取页面的截图,那么很多人都有同样的问题。抓取截图进行调整大小后,您始终可以使用上面第1点中提到的解决方案。 Webkit2png是实现同样功能的好工具。

http://www.paulhammond.org/webkit2png/