使用我很新的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