Очистка списка элементов и привязка его к одному свойству - PullRequest
1 голос
/ 24 апреля 2019

Мой текущий паук анализирует только свойства продукта, а не item['title']. Как мне все это объединить Пример страницы:

https://universalmotors.ru/motorcycles/lifan/motorcycle-lifan-lf150-13-2017/

Мой паук:

# -*- coding: utf-8 -*-
from scrapy.spiders import SitemapSpider as CrawlSpider
from ..items import DistPracticalItem


class SitemapSpider(CrawlSpider):
    name = 'sitemap3'
    allowed_domains = ['universalmotors.ru']
    sitemap_urls = ['https://universalmotors.ru/sitemap.xml']
    # sitemap_follow = ['deal']
    # sitemap_rules = [(r'^https?://sz.*deal/[0-8]{1,8}\.html$', 'parse_item')]
    sitemap_rules = [('/motorcycles/', 'parse_item')]

    def parse_item(self, response):
        item = DistPracticalItem()
      #  item['name'] = response.xpath('//h1[contains(@class,"good__title")]/text()').extract_first()
        item['title'] = response.css("h1.good__title::text").extract()
     #   prop = response.xpath('normalize-space(//tr[@itemprop="additionalProperty"])').extract()
        item['price'] = response.css('div.deal-info span.campaign-price').css('::text').extract_first()
     #   item['comments'] = response.css('div.comment div.total').css('::text').extract()
#        return item
     #   for item in response.xpath('//tr[@itemprop="additionalProperty"]'):
        for item in response.xpath('//tr[@itemprop="additionalProperty"]'):
           yield {
                'name': item.xpath('normalize-space(./*[@class="label_table"])').extract_first(),
                'value': item.xpath('normalize-space(./*[@class="value_table"])').extract_first(),
#                'title': response.css("h1.good__title::text").extract()
            }

Моя цель - получить список очищенных элементов, который будет содержать список свойств следующим образом:

Title of the Item 1| Price 1 | Property 1, Property 2, property 3
Title of the Item 2| Price 2 | Property 1, Property 2, property 3
Title of the Item 3| Price 3 | Property 1, Property 2, property 3

1 Ответ

1 голос
/ 24 апреля 2019

Вы должны получить полный элемент, который хотите очистить, ваш код дает только свойства, а не заголовок и цену.

Я изменил ваш код, и он, кажется, работает как задумано. Я удалил элемент include и некоторые комментарии, чтобы он работал на моем компьютере.

from scrapy.spiders import SitemapSpider as CrawlSpider


class SitemapSpider(CrawlSpider):
    name = 'sitemap3'
    allowed_domains = ['universalmotors.ru']
    sitemap_urls = ['https://universalmotors.ru/sitemap.xml']
    sitemap_rules = [('/motorcycles/', 'parse_item')]

    def parse_item(self, response):
        item = dict()
        item['title'] = response.css("h1.good__title::text").extract_first()
        item['price'] = response.css('div.deal-info span.campaign-price').css('::text').extract_first()
        item['properties'] = list()
        for prop in response.xpath('//tr[@itemprop="additionalProperty"]'):
            item['properties'].append(
                {
                    'name': prop.xpath('normalize-space(./*[@class="label_table"])').extract_first(),
                    'value': prop.xpath('normalize-space(./*[@class="value_table"])').extract_first(),
                }
            )
        yield item

Обратите внимание, что я собираю всю информацию внутри переменной item, которая в данном случае dict, а у вас DistPracticalItem.

В результате вы получите следующую схему:

{
  'title': string,
  'price': string,
  'properties': list of dicts with 'name' and 'value' as strings
}

Надеюсь, я был чист.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...