我知道这个问题看起来和这里的许多其他问题完全一样,因为我只是阅读了所有这些问题,他们都说要做我已经尝试过的事情,但它没有奏效(或者我错过了与我的情况)。这是我的情况:
我正在使用 Scrapy 和 Python 2.7.11 编写一个爬虫,我的代码如下所示(这是一个复制和粘贴,省略了不相关的行,但我可以根据要求重新添加它们):
class LbcSubtopicSpider(scrapy.Spider):
...omitted...
rawTranscripts = []
rawTranslations = []
def parse(self, response):
#global rawTranscripts, rawTranslations
rawTitles = []
rawVideos = []
for sel in response.xpath('//ul[1]'): #only scrape the first list
...omitted...
index = 0
for sub in sel.xpath('li/ul/li/a'): #scrape the sublist items
index += 1
if index%2!=0: #odd numbered entries are the transcripts
transcriptLink = sub.xpath('@href').extract()
#url = response.urljoin(transcriptLink[0])
#yield scrapy.Request(url, callback=self.parse_transcript)
else: #even numbered entries are the translations
translationLink = sub.xpath('@href').extract()
url = response.urljoin(translationLink[0])
yield scrapy.Request(url, callback=self.parse_translation)
print rawTitles
print rawVideos
print rawTranslations
def parse_translation(self, response):
global rawTranslations
for sel in response.xpath('//p[not(@class)]'):
rawTranslation = sel.xpath('text()').extract()
rawTranslations.append(rawTranslation)
这将在任何时候调用“print rawTranslations”或“rawTranslations.append(rawTranslation)”时返回错误,因为未定义全局“rawTranslations”。
正如我之前所说,我已经非常广泛地研究了这个问题,互联网上几乎每个人都说只需在您要使用/修改它的任何函数的开头添加一个“全局(名称)”行(尽管我从来没有分配给它,所以我什至不需要这个)。无论我的全局行是否被注释掉,我都会得到相同的结果。这种行为似乎违背了我所读到的关于全局变量在 Python 中如何工作的所有内容,所以我怀疑这可能是与如何通过 scrapy.Request(....) 调用解析函数有关的 Scrapy 怪癖。
很抱歉发布了您已经多次看到的同一个问题,但这次似乎有点扭曲,希望有人能查个水落石出。谢谢。
最佳答案
在您的情况下,您要访问的变量不是全局的,它在类的范围内。
global_var = "global"
class Example:
class_var = "class"
def __init__(self):
self.instance_var = "instance"
def check(self):
print(instance_var) # error
print(self.instance_var) # works
print(class_var) # error
print(self.class_var) # works, lookup goes "up" to the class
print(global_var) # works
print(self.global_var) # works not
如果你想写入一个全局变量,你只需要global
关键字。提示:不要这样做,因为写入的全局变量只会带来痛苦和绝望。仅将全局变量用作(配置)常量。
global_var = "global"
class Example:
def ex1(self):
global_var = "local" # creates a new local variable named "global_var"
def ex2(self):
global global_var
global_var = "local" # changes the global variable
Example().ex1()
print(global_var) # will still be "global"
Example().ex2()
print(global_var) # willnow be "local"
关于python - 函数中无法识别全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38226310/