2012-08-16 40 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/