我知道這個問題看起來和其他很多其他的一樣,因爲我只是讀了所有的東西,他們都說要做我已經嘗試過的東西,我錯過了與我的情況有細微差別)。這是我的情況:全局變量在函數中沒有識別
我正在使用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)
這將返回一個錯誤的任何時間「打印rawTranslations」還是因爲全球「rawTranslations」沒有定義「rawTranslations.append(rawTranslation)」之稱。
正如我之前說過的,我已經深入研究了這個問題,並且幾乎所有互聯網上的人都說要在任何函數的開始處添加一個「全局(名稱)」行來使用/修改它雖然我沒有分配過它,所以我甚至不需要這個)。無論我的全局行被註釋掉了,我都會得到相同的結果。這種行爲似乎違背了我讀過的有關全局變量在Python中的工作原理的所有內容,所以我懷疑這可能是一種Scrapy怪癖,與通過scrapy.Request(....)調用解析函數的方式有關。
道歉發佈似乎是你再次看到的同樣的問題,但它似乎有點扭曲這一次,希望有人可以得到它的底部。謝謝。
它看起來像你的縮進是關閉的,例如函數'parse'肯定是類「LbcSubtopicSpider」的一個方法?另外它看起來像rawTranslations不是一個全局屬性,而是一個類屬性。當然,解決方案是使用'self.rawTranslations'或'LbcSubtopicSpider.rawTranslations'(取決於上下文)。 – syntonym
當我將它粘貼在這裏時,縮進實際上被破壞 - 將修復它。至於全球/類別屬性點:我想我甚至沒有考慮過會有什麼區別。這可能是大部分使用Java編寫代碼並在類中做所有事情的產物...... – jah
'rawTranslations'不是全局的,它是一個類變量... – MisterMiyagi