2011-04-09 46 views
0
import httplib 
import re 

md5 = raw_input('Enter MD5: ') 

conn = httplib.HTTPConnection("www.md5.rednoize.com") 
conn.request("GET", "?q="+ md5) 
try: 
    response = conn.getresponse() 
    data = response.read() 
    result = re.findall('<div id="result" >(.+?)</div', data) 
    print result 
except: 
    print "couldnt find the hash" 

raw_input() 

我知道我可能实现了错误的代码,但应该使用哪个异常呢?如果它找不到散列,然后引发异常并打印“找不到散列”md5使用异常搜索

+0

我想鼓励使用名为例外,比如'除了IOError'为处理异常(python 3会将非命名异常标记为错误)。这会帮助你更好地理解这个特定的问题。 – 2011-04-09 18:52:54

回答

2

由于re.findall不会引发异常,这可能不是您想要检查结果的方式。相反,你可以写类似

result = re.findall('<div id="result" >(.+?)</div', data) 
if result: 
    print result 
else: 
    print 'Could not find the hash' 
1

如果你真的想有一个例外,你有来定义它:

class MyError(Exception): 
    def init(self, value): 
     self.value = value 
    def str(self): 
     return repr(self.value)

try: response = conn.getresponse() data = response.read() result = re.findall('(.+?)</div', data) if not result: raise MyError("Could not find the hash") except MyError: raise