scrapy 一个class中怎么写个全局变量
在Scrapy中,可以在类的__init__方法中定义全局变量。这样,该变量将在整个类中都可访问。
以下是一个示例:
import scrapy
class MySpider(scrapy.Spider):
name = 'myspider'
allowed_domains = ['example.com']
start_urls = ['http://example.com']
def __init__(self, *args, **kwargs):
super(MySpider, self).__init__(*args, **kwargs)
self.global_variable = 'Hello, World!'
def parse(self, response):
# 在parse方法中可以访问self.global_variable
print(self.global_variable)
在上面的示例中,global_variable就是一个全局变量,可以在类中的任何方法中访问。在parse方法中,我们打印了该变量的值。
请注意,在Scrapy中,每个Spider实例都是独立的,因此每个Spider实例都有自己的变量。如果您想要在多个Spider实例之间共享变量,可以考虑使用Scrapy的Settings来实现
原文地址: http://www.cveoy.top/t/topic/iim0 著作权归作者所有。请勿转载和采集!