Scrapy:无法从页面中提取所有数据

时间:2018-09-08 16:33:46

标签: python xpath web-scraping scrapy

我正在尝试从this page抓取。我写的代码从36条中刮掉了10条,我找不到问题。

如果我在外壳上单独运行查询,似乎从页面中提取了所有数据项,但是当我运行Spider时,并不是所有数据都提取到了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 :(得分:1)

如果您查看Spider的日志输出,问题将变得很明显。

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(),
# ...

答案 1 :(得分:0)

现在下面的代码似乎可以正常工作。

# -*- 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