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()
我知道我可能实现了错误的代码,但我应该使用哪个异常呢?如果它找不到散列然后引发异常并打印&#34;无法找到散列&#34;
答案 0 :(得分:2)
由于re.findall不会引发异常,因此可能不是您想要检查结果的方式。相反,你可以写一些类似
的东西result = re.findall('<div id="result" >(.+?)</div', data)
if result:
print result
else:
print 'Could not find the hash'
答案 1 :(得分: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