跳到主内容

scrapy输出第一个元素

· 1分钟阅读

I use .extract() to get the data from a xpath, like:

response.xpath('//*@id="bakery"]/span[2]/text()').extract()

the issue with this is that I always get a list as response. for example:

['23']

I only want the number, so I try with:

response.xpath('//*@id="bakery"]/span[2]/text()').extract()[0]

but this is a problem is the list empty, although I can use an exception to handle that scenario I guess there is a better way to do it

解决方法

.extract_first() to the rescue:

response.xpath('//*@id="bakery"]/span[2]/text()').extract_first()

Instead of an exception, it would return None if no elements were matched.