十九、通过Scrapy提供的API在程序中启动爬虫
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了十九、通过Scrapy提供的API在程序中启动爬虫,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2087字,纯文字阅读大概需要3分钟。
内容图文
Scrapy在Twisted异步网络库上构建,所以如果程序必须在Twisted reactor里运行
1、方式一:使用CrawlerProcess类
CrawlerProcess类(scrapy.crawler.CrawlerProcess)内部将会开启Twisted reactor、配置log和设置Twisted reactor自动关闭。
可以在CrawlerProcess初始化时传入设置的参数,使用crawl方式运行指定的爬虫类。
```
if __name__=="__main__":
process = CrawlerProcess(
{
"USER_AGENT":"Mozilla/5.0 ....",
}
)
process.crawl(爬虫类)
process.start()
```
也可以在CrawlerProcess初始化时传入项目的settings信息,在crawl方法中传入爬虫的名字。
```
if __name__=="__main__":
process = CrawlerProcess(
project_settings()
)
process.crawl(爬虫名)
process.start()
```
2、方式二:使用CrawlerRunner
使用CrawlerRunner时,在spider运行结束后,必须自行关闭Twisted reactor,需要在CrawlerRunner.crawl所返回的对象中添加回调函数。
```
if __name__=="__main__":
configure_logging({"LOG_FORMAT":"%(levelname)s:%(message)s"}) # 使用configure_logging配置了日志信息的打印格式
runner = CrawlerRunner()
d = runner.crawl(爬虫类) # 通过CrawlerRunner的crawl方法添加爬虫
d.addBoth(lambda _:reactor.stop()) # 通过addBoth添加关闭Twisted reactor的回调函数
reactor.run()
```
3、在一个进程中启动多个爬虫
1、CrawlerProcess方式实现
```
import scrapy
from scrapy.crawler import CrawlerProcess
class Myspider_1(scrapy.Spider):
...
class Myspider_2(scrapy.Spider):
...
process = CrawlerProcess()
process.crawl(Myspider_1)
process.crawl(Myspider_2)
process.start()
```
2、CrawlerRunner方式实现
1、第一种方式
```
import scrapy
from twisted.internet import reactor
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
class Myspider_1(scrapy.Spider):
...
class Myspider_2(scrapy.Spider):
...
configure_logging()
runner = CralwerRunner()
runner.crawl(Myspider_1)
runner.crawl(Myspider_2)
d = runner.join()
d.addBoth(lambda _: reactor.stop())
reactor.run()
```
2、第二种方式
```
from twisted.internet import reactor,defer
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
class Myspider_1(scrapy.Spider):
...
class Myspider_2(scrapy.Spider):
...
configure_logging()
runner = CrawlerRunner()
@defer.inlineCallbacks
def crawl():
yield runner.crawl(Myspider_1)
yield runner.crawl(Myspider_2)
reactor.stop()
crawl()
reactor.run()
```
原文:https://www.cnblogs.com/nuochengze/p/13151485.html
内容总结
以上是互联网集市为您收集整理的十九、通过Scrapy提供的API在程序中启动爬虫全部内容,希望文章能够帮你解决十九、通过Scrapy提供的API在程序中启动爬虫所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。