繁体   English   中英

尝试异常处理时出错…除了3种可能的情况

[英]Error with Exception handling try…except with 3 possible cases

我正在做网页抓取。 我需要提取一个数据字段(典型),并且有3种可能的情况:

try:
#1st case
typo = int(response.xpath('//td[contains(text(),"Chambres")]/following- 
sibling::td[@class="right"]/text()').extract()[0])                       
except: 
#2nd case when the 1st case gives an IndexError    
typo = int(sel1.xpath('//td[contains(text(),"Pièces (nombre total)")]/following-sibling::td[@class="right"]/text()').extract()[0])
except IndexError: 
#3rd case, when the first and second case give IndexError       
typo = 0

我有执行错误(必须是最后一个)

您需要嵌套的try语句:

try:
    x = response.xpath('//td[contains(text(),"Chambres")]/following-sibling::td[@class="right"]/text()')
    typo = int(x.extract()[0])
except IndexError:
    try:
        x = sel1.xpath('//td[contains(text(),"Pièces (nombre total)")]/following-sibling::td[@class="right"]/text()')
        typo = int(x.extract()[0])
    except IndexError:
        typo = 0

您可以使用循环将其简化一些:

attempts = [
    (response.xpath, '//td...'),
    (sel1.xpath, '/td...'),
]
typo = 0
for f, arg in attempts:
    try:
        typo = int(f(arg).extract()[0])
    except IndexError:
        continue

typo已初始化为后备值,但如果任何一个尝试的解析成功都将被覆盖。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM