2013-02-24 131 views
0

好吧,我對python相當陌生,我正在製作一個控制檯女巫將允許多個功能,其中一個是抓取頁面源並將其打印在頁面上,或者如果他們有另一個arg命名該arg的文件...第一個arg將是網站URL來抓取源。Python隱藏錯誤

我進口:

import os, urllib.request 

這是我的代碼:

def grab(command, args, argslist): 
    if args == "": 
     print("The " + command + " command wan't used correctly type help " + command + " for help...") 
    if args != "": 
     print("This may take a second...") 
     try: 
      argslistcheck = argslist[0] 
      if argslistcheck[0:7] != "http://": 
       argslist[0] = "http://" + argslist[0] 
      with urllib.request.urlopen(argslist[0]) as url: 
       source = url.read() 
       source = str(source, "utf-8") 
     except IndexError: 
      print("Couln't connect") 
      source = "" 
     try: 
      filesourcename = argslist[1] + ".txt" 
      filesourceopen = open(filesourcename, "w") 
      filesourceopen.write(source) 
      filesourceopen.close() 
      print("You can find the file save in " + os.getcwd() + " named " + argslist[1] + ".txt.") 
     except IndexError: 
      print(source) 

現在,當我將確定與現在我專注於主要的一點改善我的代碼。現在它可以工作,我稍後會改進代碼,唯一的問題是,如果用戶輸入一個假的網站或一個不存在的網站頁面,那麼它會返回很多錯誤。然而,如果我改變:

except IndexError: 
    print("Coulnd't connect") 
    source = "" 

只是:

except: 
    print("Couldn't connect") 
    source = "" 

然後它總是說無法連接...

任何幫助嗎?我沒有把我的代碼的其餘部分,因爲我認爲它不會有用,如果你需要它,我可以把它放在一邊。

我標題爲隱藏錯誤的原因是因爲它仍然有效,因爲它只是說它無法連接,如果用戶輸入第二個參數,那麼它會將源保存到他命名的文件中。

+0

而不是扔'嘗試:除了:'當你得到錯誤,你有沒有想過實際上避免錯誤的第一位? – Eric 2013-02-24 19:47:06

+0

你是什麼意思?如果我能避免這個錯誤,那麼是的,我也想這樣做。 – TrevorPeyton 2013-02-24 19:49:12

+0

爲什麼你首先得到'IndexError's? – Eric 2013-02-24 19:53:18

回答

1
try: 
    argslistcheck = argslist[0] 
    if argslistcheck[0:4] != "http://": 
     argslist[0] = "http://" + argslist[0] 
    with urllib.request.urlopen(argslist[0]) as url: 
     source = url.read() 
     source = str(source, "utf-8") 
except IndexError: 
    print("Couln't connect") 
    source = "" 

在該代碼塊,即可以引發IndexError異常的惟一事情是argslist[0]。如果該列表中沒有元素,則會發生這種情況。這很可能不是你的問題。

現在如果輸入了無效地址,urlopen將會失敗。但它不會增加IndexError,而是增加urllib.error.URLError或更專門的urllib.error.HTTPError

如果您只寫except IndexError您只會發現該錯誤,但不會產生urlopen引發的異常。如果你想趕上那些爲好,你得再添except情況:

except IndexError: 
    print('Argument is missing') 
except urllib.error.URLError: 
    print('Could not connect to the URL.') 

另一種方法是正好趕上任何例外,僅通過不指定任何(這是你在最後的代碼做了什麼) 。請注意,通常不建議這樣做,因爲它會隱藏您可能預期不會發生的任何異常;即它會隱藏錯誤。所以如果你知道只有一些可能的例外,那就趕緊捕捉並明確處理它們。

+0

我不知道你可以指定那麼多,謝謝! – TrevorPeyton 2013-02-24 19:59:54

+0

@TrevorPeyton然後,您可能會對本教程的[this part](http://docs.python.org/3/tutorial/errors.html)感興趣,以獲取更多信息:) – poke 2013-02-24 20:01:05