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()

我知道我可能执行错误的代码,但我应该为此使用哪个异常?如果找不到哈希,则引发异常并打印“找不到哈希”

4

2 回答 2

2

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

result = re.findall('<div id="result" >(.+?)</div', data)
if result:
    print result
else:
    print 'Could not find the hash'
于 2011-04-09T18:44:33.183 回答
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

于 2011-04-09T19:04:12.267 回答