异常处理尝试出错...除了 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 被初始化为回退值,但如果任一尝试解析成功,将被覆盖。