【问题标题】:Scrapy Amazon SpiderScrapy 亚马逊蜘蛛
【发布时间】:2018-03-25 12:42:42
【问题描述】:

我正在尝试抓取亚马逊,但我获得的 fhe file.csv 是空白的。 看看我的代码:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.exceptions import CloseSpider
from mercado.items import MercadoItem


class MercadoSpider(CrawlSpider):
    name = 'mercado'
    item_count = 0
    allowed_domain = ['www.amazon.es']
    start_urls = ['https://www.amazon.es/s/ref=sr_st_price-asc-rank?keywords=febi+bilstein&rh=i%3Aaps%2Ck%3Afebi+bilstein&__mk_es_ES=%C3%85M%C3%85Z%C3%95%C3%91&qid=1521977786&sort=price-asc-rank']

    rules = {

        Rule(LinkExtractor(allow =(), restrict_xpaths = ('//*[@id="pagnNextString"]'))),
        Rule(LinkExtractor(allow =(), restrict_xpaths = ('//h2')),
                        callback = 'parse_item', follow = False)
    }


    def parse_item(self, response):
        ml_item = MercadoItem()

        #info de producto
        ml_item['articulo'] = response.xpath('//*[@id="result_0"]/div/div/div/div[2]/div[1]/div[1]/a/h2').extract()
        ml_item['precio'] = response.xpath('//*[@id="result_0"]/div/div/div/div[2]/div[2]/div[1]/div[1]/a/span[2]').extract()
        self.item_count += 1
        if self.item_count > 10:
            raise CloseSpider('item_exceeded')
        yield ml_item

我不知道为什么我没有得到结果。 你能帮帮我吗?

【问题讨论】:

    标签: python web-scraping scrapy scrapy-spider


    【解决方案1】:

    您的第二个LinkExtractor 尝试提取h2 元素中的所有链接。
    要匹配包含h2 元素的所有链接,您可以使用像//a[h2] 这样的xpath

    修复该问题后,您将遇到parse_item 中的 xpath 不匹配任何内容的问题,因此您也需要修复这些问题。

    另外,为了在抓取一定数量的项目后关闭蜘蛛,还有CLOSESPIDER_ITEMCOUNT 设置。

    【讨论】:

    • 非常感谢!你是对的。现在它起作用了。我现在遇到的问题是“503 服务不可用”,所以我被阻止了。你知道如何在代码中添加“用户代理”来避免这种情况吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多