I currently have a problem about my scrapy code : I am scrapping a website, and trying to fetch a data. Sometimes in some pages, this data doesn't exist, and then I have the very well known indexerror, as expected. But all the record attached to it is neither put in the output file : that's annoying.
How can I find a solution for that? I tried with a if response.xpath("whatever_data")="":.. else..
I tried to make a try methode, I tried to except the indexerror .. nothing worked.
Any idea?
Here is my code :
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = ['http://www.verif.com/recherche/?search=v/1/ca/h_siren=&h_code_ape=2060Z']
def parse(self, response):
for lien_fiche in response.css('a::attr(href)').re(r'\/societe\/.+'):
yield scrapy.Request(response.urljoin(lien_fiche), callback=self.parse_fiche)
next_page = response.css('a.btn-page.btn-next::attr(onclick)').re(r'/recherche.+2060Z')[0]
if next_page is not None:
next_page = response.urljoin(next_page)
yield scrapy.Request(next_page, callback=self.parse)
def parse_fiche(self, response):
code_ape = "2060Z"
yield {
'nom': response.xpath('//td[@class="tdhead"][text()="Raison sociale "]/following-sibling::td/text()').extract_first(),
'CA 2015' : response.xpath('//td[@class="tdhead"][text()="Chiffre d\'affaires 2015 "]/following-sibling::td/a/text()').re(r'\n\s+([0-9€ ]+)'),
'Capital social' : response.xpath('//td[@class="tdhead"][text()="Capital Social "]/following-sibling::td/text()').extract_first(),
'SIRET': response.xpath('//td[@class="tdhead"][text()="SIRET "]/following-sibling::td/text()').extract_first(),
'code APE': code_ape,
'effectif': response.css('script').re(r'=(effectif.+);ca'),
'dirigeant':
response.xpath('//table[@class="table table-default dirigeants"]/tr/td[@class="tdhead"]/text()')[
0].extract() + " " + response.xpath(
'//table[@class="table table-default dirigeants"]/tr/td[@class="tdhead"]/following-sibling::td/a/text()')[
0].extract(),
}
Best,
Thanks for the feedback, I finally chose a try/except method :)