scrapy一般使用方式,都是通过编写一个Spider,然后通过命令行执行指令,来开启一个爬虫并执行,例如:
1
| scrapy runspider quotes_spider.py -o quotes.json
|
这种方式不太适合大型项目以及定制化爬取,所以需要想办法调用scrapy接口,来实现代码中调用。
一种常用做法是使用scrapyd或者scrapy-cloud,这里我们都不使用。
使用CrawlerProcess
scrapy.crawler.CrawlerProcess会创建一个Twisted reactor,设置好日志格式和shutdown handlers。Crawler本身也是使用该类启动的爬虫
下方是一个简单例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import scrapy from scrapy.crawler import CrawlerProcess
class MySpider(scrapy.Spider): ...
process = CrawlerProcess(settings={ 'FEED_FORMAT': 'json', 'FEED_URI': 'items.json' })
process.crawl(MySpider) process.start()
|
使用CrawlerRunner
scrapy.crawler.CrawlerRunner类提供了更多可控性,不会创建reactor,也不会干扰现有的reactor。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| from twisted.internet import reactor import scrapy from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging
class MySpider(scrapy.Spider): ...
configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s'}) runner = CrawlerRunner()
d = runner.crawl(MySpider) d.addBoth(lambda _: reactor.stop()) reactor.run()
|