我有两段代码:
try:
error1=tree.xpath[...]
error2=tree.xpath[...]
except IndexError:
print 'hello' #piece 1
try:
error3=tree.xpath[...]
error4=tree.xpath[...]
except IndexError:
print 'hello' #piece 2
取决于xpath pattern
是什么,两件中的一件效果很好。例如,对于某些网站,第1部分工作正常(因此我必须对第2部分进行评论)而对于其他一些网站,第2部分工作正常(因此我必须对第1部分进行评论)。
如何在我使用的所有网站的所有条件下混合使用这两件作品?
答案 0 :(得分:0)
您可以嵌套例外:
try:
error1=tree.xpath[...]
error2=tree.xpath[...]
print "Method 1 succeed"
except IndexError:
print "Method 1 failed, trying method 2"
try:
error3=tree.xpath[...]
error4=tree.xpath[...]
print "Method 2 succeed"
except IndexError:
print 'Both method failed'
答案 1 :(得分:0)
您可以通过引入一个新变量来使用相同的代码,该变量会检查命令是否成功。
swap(a, b)