笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册

常用做法

发布者: 笨鸟自学网

本节记录使用Scrapy时的常见做法。这些内容涵盖了许多主题,通常不属于任何其他特定部分。

从脚本中运行Scrapy

你可以使用 API 从脚本运行scrapy,而不是运行scrapy via的典型方式 scrapy crawl .

记住,scrappy构建在TwistedAsynchronicNetworkLibrary之上,所以需要在TwistedReactor中运行它。

你能用来运行蜘蛛的第一个工具是 scrapy.crawler.CrawlerProcess . 这个类将为您启动一个扭曲的反应器,配置日志记录和设置关闭处理程序。这个类是所有slapy命令使用的类。

下面是一个示例,演示如何使用它运行单个蜘蛛。

import scrapy
from scrapy.crawler import CrawlerProcess

class MySpider(scrapy.Spider):
    # Your spider definition
    ...

process = CrawlerProcess(settings={
    "FEEDS": {
        "items.json": {"format": "json"},
    },
})

process.crawl(MySpider)
process.start() # the script will block here until the crawling is finished

在CrawlerProcess中定义字典中的设置。一定要检查 CrawlerProcess 了解其使用细节的文档。

如果您在一个零碎的项目中,有一些额外的帮助器可以用来导入项目中的那些组件。你可以自动输入蜘蛛的名字 CrawlerProcess 及使用 get_project_settings 得到一个 Settings 具有项目设置的实例。

下面是一个如何使用 testspiders 以项目为例。

from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings

process = CrawlerProcess(get_project_settings())

# 'followall' is the name of one of the spiders of the project.
process.crawl('followall', domain='scrapy.org')
process.start() # the script will block here until the crawling is finished

还有另一个Scrapy实用程序,它提供了对爬行过程的更多控制: scrapy.crawler.CrawlerRunner . 这个类是一个薄包装器,它封装了一些简单的帮助器来运行多个爬行器,但是它不会以任何方式启动或干扰现有的反应器。

使用这个类,在调度spider之后应该显式地运行reactor。建议您使用 CrawlerRunner 而不是 CrawlerProcess 如果您的应用程序已经在使用Twisted,并且您希望在同一个反应器中运行Scrapy。

请注意,蜘蛛完成后,您还必须自己关闭扭曲的反应堆。这可以通过将回调添加到由 CrawlerRunner.crawl 方法。

下面是一个使用它的例子,以及在 MySpider 已完成运行。

from twisted.internet import reactor
import scrapy
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging

class MySpider(scrapy.Spider):
    # Your spider definition
    ...

configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s'})
runner = CrawlerRunner()

d = runner.crawl(MySpider)
d.addBoth(lambda _: reactor.stop())
reactor.run() # the script will block here until the crawling is finished

参见

Reactor Overview


123下一页
上一篇:蜘蛛合约下一篇:宽爬行

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-7-27 14:13 , Processed in 0.020819 second(s), 17 queries .

© 2001-2020

返回顶部