我想建立一个爬虫,需要抓取网页的网址,并将结果返回给一个网页。现在,我从终端启动scrapy并将响应存储在一个文件中。当一些输入发布到Flask、处理并返回响应时,我如何启动爬虫?
发布于 2015-07-24 12:16:14
您需要在Flask应用程序中创建一个CrawlerProcess,并以编程方式运行爬网。请参阅docs。
import scrapy
from scrapy.crawler import CrawlerProcess
class MySpider(scrapy.Spider):
# Your spider definition
...
process = CrawlerProcess({
'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})
process.crawl(MySpider)
process.start() # The script will block here until the crawl is finished在继续您的项目之前,我建议您查看Python任务队列(如rq)。这将允许您在后台运行Scrapy crawls,并且在scrapes运行时Flask应用程序不会冻结。
https://stackoverflow.com/questions/31601848
复制相似问题