【问题标题】:Unable to scrape while running scrapy spider sequentially顺序运行scrapy spider时无法抓取
【发布时间】:2018-12-20 21:54:48
【问题描述】:

我是scrapy的新手,我正在尝试使用示例进行练习,我想按顺序运行scrapy spider,但是当我使用文档中的代码时 (https://doc.scrapy.org/en/latest/topics/practices.html#run-scrapy-from-a-script) 在使用爬虫进程时它不起作用。蜘蛛会立即打开和关闭,而不会从网站上抓取数据。但是当我使用“scrapy crawl”单独运行蜘蛛时,它可以工作。我不明白为什么蜘蛛在我单独调用它时会抓取数据,而在我尝试按顺序运行它时不会抓取数据。如果有人可以帮助我,那就太好了。 这是我正在使用的代码:

class APASpider(scrapy.Spider):
name = 'APA_test'
allowed_domains = ['some_domain.com']
start_urls = ['startin_url']



def start_requests(self):
    for url in self.start_urls:
        yield SplashRequest(url, self.parse,
        endpoint='execute',
        cache_args=['lua_source'],
        args={'lua_source': script,'timeout': 3600},
        headers={'X-My-Header': 'value'},
        )

def parse(self, response):

    for href in response.xpath('//a[@class="product-link"]/@href').extract():            
        yield SplashRequest(response.urljoin(href),self.parse_produits,
        endpoint='execute',
        cache_args=['lua_source'],
        args={'lua_source': script,'timeout': 3600},
        headers={'X-My-Header': 'value'},
        )


    for pages in response.xpath('//*[@id="loadmore"]/@href'):
        yield SplashRequest(response.urljoin(pages.extract()),self.parse,
        endpoint='execute',
        cache_args=['lua_source'],
        args={'lua_source': script,'timeout': 3600},
        headers={'X-My-Header': 'value'},
        )



def parse_produits(self,response):

    Nom = response.xpath("//h1/text()").extract()
    Poids = response.xpath('//p[@class="description"]/text()').extract()
    item_APA = APAitem()
    item_APA["Titre"] = Nom
    item_APA["Poids"] = Poids
    yield item_APA

configure_logging()
runner = CrawlerRunner()


@defer.inlineCallbacks
def crawl():
yield runner.crawl(APASpider)
reactor.stop()

crawl()
reactor.run() # the script will block here until the last crawl call is finished

谢谢

【问题讨论】:

    标签: python web-scraping scrapy scrapy-spider


    【解决方案1】:

    考虑到问题中没有提供日志消息,很难确切地说出问题所在。

    话虽如此,我仍然会尝试回答,因为我前段时间遇到过同样的问题。

    scrapy_splash 存在 this 问题,涉及 Splash 脚本上的 local last_response = entries[#entries].response。我假设你和我一样在你的脚本中有它。

    我使用的解决方法是在获取最后一个条目之前检查历史记录是否不为空。(由 github 用户 kmike 建议)。

    【讨论】:

    • 考虑到问题确实是 Splash 脚本,我建议您浏览 scrapy_splash github 问题页面,因为可能有更好的解决方法。
    猜你喜欢
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 2020-10-03
    相关资源
    最近更新 更多