使用我很新的Scrapy,想尝试以下操作: 从网页中提取一些值,将其存储在一个变量,在我的主要脚本中使用它。 所以我也跟着他们的教程,并改变了代码为我的目的: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...
这将工作至今,但我敢肯定它不是一个良好的作风,甚至有一些不良的副作用,如果我定义标题变量为全局。 如果我跳过那一行,那么我会得到“未定义的变量”错误当然是:/ 因此,我正在寻找一种方法来返回变量并在我的主脚本中使用它。
我已阅读关于物品管道,但我无法使其工作。
任何帮助/想法都非常感谢:) 在此先感谢!
更好地利用'global' - 它会更容易。管道不会帮助你。 – furas