Как отсканировать результаты каждого поиска и вернуть? - PullRequest
0 голосов
/ 11 мая 2019

Я пытался почерпнуть некоторую информацию из реестра компаний. Что работает, но я хочу повторить это для каждого результата, указанного в поисковой записи. Я пытался использовать linkextractors, но я не получаю его на работу.

Страница результатов поиска: https://www.companiesintheuk.co.uk/Company/Find?q=a

Очистка отдельных результатов из элементов поиска работает (если я нажимаю на элемент результатов), но как мне повторить это для каждого элемента результатов?

Вот мой код:

import scrapy
import re
from scrapy.linkextractors import LinkExtractor

class QuotesSpider(scrapy.Spider):


  name = 'CYRecursive'
  start_urls = [
      'https://www.companiesintheuk.co.uk/ltd/a-2']

  def parse(self, response):

    # Looping throught the searchResult block and yielding it
    for i in response.css('div.col-md-9'):

        for i in response.css('div.col-md-6'):
          yield {
              'company_name': re.sub('\s+', ' ', ''.join(i.css('#content2 > strong:nth-child(2) > strong:nth-child(1) > div:nth-child(1)::text').get())),
              'address': re.sub('\s+', ' ', ''.join(i.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > span:nth-child(1)::text").extract_first())),
              'location': re.sub('\s+', ' ', ''.join(i.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > span:nth-child(3)::text").extract_first())),
              'postal_code': re.sub('\s+', ' ', ''.join(i.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > a:nth-child(5) > span:nth-child(1)::text").extract_first())),
          }

1 Ответ

1 голос
/ 12 мая 2019
import scrapy
import re
from scrapy.linkextractors import LinkExtractor


class QuotesSpider(scrapy.Spider):

    name = 'CYRecursive'
    start_urls = [
        'https://www.companiesintheuk.co.uk/Company/Find?q=a']

    def parse(self, response):

        for company_url in response.xpath('//div[@class="search_result_title"]/a/@href').extract():
            yield scrapy.Request(
                url=response.urljoin(company_url),
                callback=self.parse_details,
            )

        next_page_url = response.xpath('//li/a[@class="pageNavNextLabel"]/@href').extract_first()
        if next_page_url:
            yield scrapy.Request(
                url=response.urljoin(next_page_url),
                callback=self.parse,
            )


    def parse_details(self, response):

        # Looping throught the searchResult block and yielding it
        for i in response.css('div.col-md-9'):

            for i in response.css('div.col-md-6'):
                yield {
                    'company_name': re.sub('\s+', ' ', ''.join(i.css('#content2 > strong:nth-child(2) > strong:nth-child(1) > div:nth-child(1)::text').get())),
                    'address': re.sub('\s+', ' ', ''.join(i.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > span:nth-child(1)::text").extract_first())),
                    'location': re.sub('\s+', ' ', ''.join(i.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > span:nth-child(3)::text").extract_first())),
                    'postal_code': re.sub('\s+', ' ', ''.join(i.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > a:nth-child(5) > span:nth-child(1)::text").extract_first())),
                }

И, конечно, вы можете использовать start_requests для автоматического yield всех поисков от a до z.

Ваши CSS-выражения неверны:

            yield {
                'company_name': response.xpath('//div[@itemprop="name"]/text()').extract_first(),
                'address': response.xpath('//span[@itemprop="streetAddress"]/text()').extract_first(),
                'location': response.xpath('//span[@itemprop="addressLocality"]/text()').extract_first(),
                'postal_code': response.xpath('//span[@itemprop="postalCode"]/text()').extract_first(),
            }
...