【问题标题】:Cannot write to global variable from Python Scrapy method无法从 Python Scrapy 方法写入全局变量
【发布时间】:2020-01-11 16:18:04
【问题描述】:

我定义了一个希望写入全局变量的 scrapy 方法:

我用占位符值设置了一个全局变量

currentTitle = 'unchanged global title'

然后我定义了scrapy spider

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    currentClassTitle = 'unchanged class title'

    def start_requests(self):
        urls = [
            #here goes my list of urls to scrape
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        title=response.xpath('/html/head/title').getall()
        title=str(title)
        title=title[9:-10]
        print(title)
        #So far so good, the title is correctly extracted and printed
        #I intend to write the title to both global currentTitle variable
        # and to class variable currentClassTitle, using method update for the latter:

        global currentTitle
        currentTitle = title
        QuotesSpider.update(title)

    def update(value):
        QuotesSpider.currentClassTitle = value

接下来是标准的scrapy东西,我不太熟悉,但在我偶然发现这个问题之前一直运行良好

def crawl ():
    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
    time.sleep(2)

def run_spider(spider):
    def f(q):
        try:
            runner = crawler.CrawlerRunner()
            deferred = runner.crawl(spider)
            deferred.addBoth(lambda _: reactor.stop())
            reactor.run()
            q.put(None)
        except Exception as e:
            q.put(e)

    q = Queue()
    p = Process(target=f, args=(q,))
    p.start()
    result = q.get()
    p.join()

    if result is not None:
        raise result

下面是一个函数,只要特定 Google Firestore 集合的任何文档具有已抓取的值:False(它更改为 True),就会触发抓取工具

def on_snapshot(col_snapshot, changes, read_time):
    docCounter = 0
    for doc in col_snapshot:
        print(u'{}'.format(doc.id))
        thisDoc_ref = db.collection(u'urls').document(doc.id)
        thisDoc_ref.update({u'capital': 'sample capital name'})
        thisDoc_ref.update({u'crawled': True})
        run_spider(QuotesSpider)
        sleep(5)
        #Just to ensure that I give the crawler enough time to process, the function sleeps after triggering the spider. 
        #Not the best practice, but good enough for testing functionality for the moment

        print(QuotesSpider.currentClassTitle)
#I get 'unchanged class title'

        print(currentTitle)
#I get 'unchanged global title'

        thisDoc_ref.update({u'title': currentTitle})
#I intend to store the document's title in Firestore using the value of currentTitle, which will not work
#because I cannot retrieve the value of title

不管怎样,从类属性 QuotesSpider.currentClassTitle 或全局变量 currentTitle 获取标题的值对我来说都可以,但它们都不起作用。运行蜘蛛时,我似乎无法更新其中任何一个的值。

【问题讨论】:

  • 嗨@Ivan!在 python 中,如果你想修改你的类实例中的一个变量,你应该使用self.currentClassTitle。如果您正在做QuotesSpider.currentClassTitle,您指的是类的变量,而不是您正在使用的实例!我希望它有帮助! :)

标签: python class scrapy global-variables


【解决方案1】:

如果您想在其类方法之一中访问特定于您的 Python 类的 实例 的变量,您想使用

self.currentClassTitle

使用QuotesSpider.currentClassTitle 访问默认类变量(当您的类未初始化时)

更多信息在这里: https://www.geeksforgeeks.org/self-in-python-class/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-14
    • 2018-12-23
    • 2023-03-04
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多