我是 Scrapy 的新手,想尝试以下方法: 从网页中提取一些值,将其存储在变量中并在我的主脚本中使用它。 因此,我遵循了他们的教程并为我的目的更改了代码:
import scrapy
from scrapy.crawler import CrawlerProcess
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
'http://quotes.toscrape.com/page/1/'
]
custom_settings = {
'LOG_ENABLED': 'False',
}
def parse(self, response):
global title # This would work, but there should be a better way
title = response.css('title::text').extract_first()
process = CrawlerProcess({
'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})
process.crawl(QuotesSpider)
process.start() # the script will block here until the crawling is finished
print(title) # Verify if it works and do some other actions later on...
到目前为止这会起作用,但我很确定这不是一个好的样式,如果我将 title 变量定义为全局变量,甚至会有一些不好的副作用。 如果我跳过那一行,那么我当然会得到“ undefined variable ”错误:/ 因此,我正在寻找一种方法来返回变量并在我的主脚本中使用它。
我已阅读有关项目管道的信息,但无法使其正常工作。
非常感谢任何帮助/想法 :) 提前致谢!
最佳答案
制作一个变量 global
应该可以满足您的需要,但正如您提到的那样,它的风格并不好。
我实际上建议使用不同的服务来进行进程间的通信,比如 Redis ,因此您的爬虫与任何其他进程之间不会发生冲突。
设置和使用非常简单,文档有一个 very simple example .
在蜘蛛内部实例化 redis 连接,并在主进程上再次实例化(将它们视为单独的进程)。蜘蛛设置变量,主进程读取(或获取
)信息。
关于python - Scrapy 将返回的项目存储在变量中以在主脚本中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47993380/