Scrapy сканирует несколько страниц с ошибкой приращения, возвращая только первую страницу - PullRequest
0 голосов
/ 29 апреля 2020

Я пытаюсь сканировать последовательные страницы, где суффикс увеличивается с шагом 20 (в зависимости от количества записей на каждой странице)

Первая страница: https://www.daft.ie/dublin-city/property-for-sale/dublin-4/

Второй: https://www.daft.ie/dublin-city/property-for-sale/dublin-4/?offset=20

и 10-я страница: https://www.daft.ie/dublin-city/property-for-sale/dublin-4/?offset=180

Я проверил отступ, и это выглядит нормально, но возвращает только первую страницу из 20 списков. Это файл spider.py, и я был бы очень признателен за любые советы

import scrapy


class DaftieSpiderSpider(scrapy.Spider):
name = 'daftie_spider'
page_number = 20
allowed_domains = ['https://www.daft.ie/dublin-city/property-for-sale/dublin-4/']
start_urls = ['https://www.daft.ie/dublin-city/property-for-sale/dublin-4/']

def parse(self, response):
    listings = response.xpath('//div[@class="PropertyCardContainer__container"]')
    for listing in listings:
        price = listing.xpath('.//a/strong[@class="PropertyInformationCommonStyles__costAmountCopy"]/text()').extract_first()
        address = listing.xpath('.//*[@class="PropertyInformationCommonStyles__addressCopy--link"]/text()').extract_first()
        bedrooms = listing.xpath('.//*[@class="QuickPropertyDetails__iconCopy"]/text()').extract_first()
        bathrooms = listing.xpath('.//*[@class="QuickPropertyDetails__iconCopy--WithBorder"]/text()').extract_first()
        prop_type = listing.xpath('.//*[@class="QuickPropertyDetails__propertyType"]/text()').extract_first()
        agent = listing.xpath('.//div[@class="BrandedHeader__agentLogoContainer"]/img/@alt').extract_first()

        yield{'price': price,
              'address': address,
              'bedrooms': bedrooms,
              'bathrooms': bathrooms,
              'prop_type': prop_type,
              'agent': agent}

        next_page = 'https://www.daft.ie/dublin-city/property-for-sale/dublin-4/?offset=' + str(DaftieSpiderSpider.page_number)
        if DaftieSpiderSpider.page_number <= 180:
            DaftieSpiderSpider.page_number += 20
            yield response.follow(next_page, callback=self.parse)

Ответы [ 2 ]

1 голос
/ 29 апреля 2020

Не уверен, что это из-за форматирования, но вы увеличиваете значение на 20 в списках l oop. В любом случае, я бы попытался не адаптировать переменную класса следующим образом.

Для меня лучше сработало следующее:

import scrapy


class DaftieSpiderSpider(scrapy.Spider):
    name = 'daftie_spider'
    page_number = 20
    allowed_domains = ['daft.ie']
    start_urls = ['https://www.daft.ie/dublin-city/property-for-sale/dublin-4/']

    def parse(self, response):
        offset = response.meta.get('offset', 0)
        listings = response.xpath('//div[@class="PropertyCardContainer__container"]')
        for listing in listings:
            price = listing.xpath('.//a/strong[@class="PropertyInformationCommonStyles__costAmountCopy"]/text()').extract_first()
            address = listing.xpath('.//*[@class="PropertyInformationCommonStyles__addressCopy--link"]/text()').extract_first()
            bedrooms = listing.xpath('.//*[@class="QuickPropertyDetails__iconCopy"]/text()').extract_first()
            bathrooms = listing.xpath('.//*[@class="QuickPropertyDetails__iconCopy--WithBorder"]/text()').extract_first()
            prop_type = listing.xpath('.//*[@class="QuickPropertyDetails__propertyType"]/text()').extract_first()
            agent = listing.xpath('.//div[@class="BrandedHeader__agentLogoContainer"]/img/@alt').extract_first()

            yield{'price': price,
                  'address': address,
                  'bedrooms': bedrooms,
                  'bathrooms': bathrooms,
                  'prop_type': prop_type,
                  'agent': agent}

        if offset <= 180:
            offset += 20
            next_page = 'https://www.daft.ie/dublin-city/property-for-sale' \
                        '/dublin-4/?offset=' + str(offset)
            yield response.follow(next_page,
                                  callback=self.parse,
                                  meta={'offset': offset})
0 голосов
/ 04 мая 2020

Окончательный код, который сработал: Большое спасибо за вашу помощь

import scrapy


class DaftieSpiderSpider(scrapy.Spider):
    name = 'daftie_spider'
    allowed_domains = ['www.daft.ie']
    page_number = 2
    start_urls = ['https://www.daft.ie/dublin-city/property-for-sale/dublin-4/?offset=0']

    def parse(self, response):
        listings = response.xpath('//div[@class="PropertyCardContainer__container"]')
    for listing in listings:
        price = listing.xpath('.//a/strong[@class="PropertyInformationCommonStyles__costAmountCopy"]/text()').extract_first()
        address = listing.xpath('.//*[@class="PropertyInformationCommonStyles__addressCopy--link"]/text()').extract_first()
        bedrooms = listing.xpath('.//*[@class="QuickPropertyDetails__iconCopy"]/text()').extract_first()
        bathrooms = listing.xpath('.//*[@class="QuickPropertyDetails__iconCopy--WithBorder"]/text()').extract_first()
        prop_type = listing.xpath('.//*[@class="QuickPropertyDetails__propertyType"]/text()').extract_first()
        agent = listing.xpath('.//div[@class="BrandedHeader__agentLogoContainer"]/img/@alt').extract_first()

        yield{'price': price,
              'address': address,
              'bedrooms': bedrooms,
              'bathrooms': bathrooms,
              'prop_type': prop_type,
              'agent': agent
        }

    next_page = 'https://www.daft.ie/dublin-city/property-for-sale/dublin-4/?offset=' + str(DaftieSpiderSpider.page_number) + '/'
    if DaftieSpiderSpider.page_number < 200:
        DaftieSpiderSpider.page_number += 20
        yield response.follow(next_page, callback=self.parse)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...