Scrapy: не могу вытащить все данные со страницы - PullRequest
0 голосов
/ 08 сентября 2018

Я пытаюсь соскрести с этой страницы . Код, который я написал, очищает 10 пунктов из 36 Я не могу найти проблему.

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

Мой код

# -*- coding: utf-8 -*-
import scrapy


class AlibabaSpider(scrapy.Spider):
    name = 'alibaba'
    allowed_domains = ['alibaba.com']
    start_urls = ['https://www.alibaba.com/catalog/agricultural-growing-media_cid144?page=1']

def parse(self, response):
    for products in response.xpath('//div[contains(@class, "m-gallery-product-item-wrap")]'):
        item = {
            'product_name': products.xpath('.//h2/a/@title').extract_first(),
            'price':  products.xpath('.//div[@class="price"]/b/text()').extract_first().strip(),
            'min_order': products.xpath('.//div[@class="min-order"]/b/text()').extract_first(),
            'company_name': products.xpath('.//div[@class="stitle util-ellipsis"]/a/@title').extract_first(),
            'prod_detail_link': products.xpath('.//div[@class="item-img-inner"]/a/@href').extract_first(),
            'response_rate': products.xpath('.//i[@class="ui2-icon ui2-icon-skip"]/text()').extract_first().strip(),
            #'image_url': products.xpath('.//div[@class=""]/').extract_first(),
         }
        yield item

Изображение моего результата

enter image description here

Результат паука только 10 пунктов соскоб

enter image description here

Видно, что все 36 наименований товаров извлечены

Ответы [ 2 ]

0 голосов
/ 09 сентября 2018

Теперь приведенный ниже код работает отлично.

# -*- coding: utf-8 -*-
import scrapy


class AlibabaSpider(scrapy.Spider):
    name = 'alibaba'
    allowed_domains = ['alibaba.com']
    start_urls = ['https://www.alibaba.com/catalog/agricultural-growing-media_cid144?page=1']

def parse(self, response):
    for products in response.xpath('//div[contains(@class, "m-gallery-product-item-wrap")]'):
        item = {
            'product_name': products.xpath('.//h2/a/@title').extract_first(),
            'price': products.xpath('.//div[@class="price"]/b/text()').extract_first('').strip(),
            'min_order': products.xpath('.//div[@class="min-order"]/b/text()').extract_first(),
            'company_name': products.xpath('.//div[@class="stitle util-ellipsis"]/a/@title').extract_first(),
            'prod_detail_link': products.xpath('.//div[@class="item-img-inner"]/a/@href').extract_first(),
            'response_rate': products.xpath('.//i[@class="ui2-icon ui2-icon-skip"]/text()').extract_first('').strip(),
            #'image_url': products.xpath('.//div[@class=""]/').extract_first(),
         }
        yield item
0 голосов
/ 08 сентября 2018

Если вы посмотрите на журнал регистрации паука, проблема становится очевидной.

Traceback (most recent call last):
  File "c:\program files\python37\lib\site-packages\scrapy\utils\defer.py", line 102, in iter_errback
    yield next(it)
  File "c:\program files\python37\lib\site-packages\scrapy\spidermiddlewares\offsite.py", line 30, in process_spider_output
    for x in result:
  File "c:\program files\python37\lib\site-packages\scrapy\spidermiddlewares\referer.py", line 339, in <genexpr>
    return (_set_referer(r) for r in result or ())
  File "c:\program files\python37\lib\site-packages\scrapy\spidermiddlewares\urllength.py", line 37, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "c:\program files\python37\lib\site-packages\scrapy\spidermiddlewares\depth.py", line 58, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "D:\Users\Ivan\Documents\Python\a.py", line 18, in parse
    'response_rate': products.xpath('.//i[@class="ui2-icon ui2-icon-skip"]/text()').extract_first().strip(),
AttributeError: 'NoneType' object has no attribute 'strip'
2018-09-08 19:40:36 [scrapy.core.engine] INFO: Closing spider (finished)
2018-09-08 19:40:36 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 262,
 'downloader/request_count': 1,
 'downloader/request_method_count/GET': 1,
 'downloader/response_bytes': 50753,
 'downloader/response_count': 1,
 'downloader/response_status_count/200': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2018, 9, 8, 17, 40, 36, 231107),
 'item_scraped_count': 9,
 'log_count/DEBUG': 11,
 'log_count/ERROR': 1,
 'log_count/INFO': 7,
 'response_received_count': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'spider_exceptions/AttributeError': 1,
 'start_time': datetime.datetime(2018, 9, 8, 17, 40, 33, 668475)}

Как видите, возникает исключение (AttributeError), потому что не все ваши элементыиметь цену и / или коэффициент отклика.

Один из возможных способов решить эту проблему - использовать другое значение по умолчанию при извлечении:

# ...
'price':  products.xpath('.//div[@class="price"]/b/text()').extract_first('').strip(),
# ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...