这涉及到几乎相同的代码,我刚才问了关于今天上午的一个不同的问题,所以如果它看起来很熟悉,那是因为它。用Scrapy填充的列表在实际填充之前被返回
class LbcSubtopicSpider(scrapy.Spider):
...irrelevant/sensitive code...
rawTranscripts = []
rawTranslations = []
def parse(self, response):
rawTitles = []
rawVideos = []
for sel in response.xpath('//ul[1]'): #only scrape the first list
...irrelevant code...
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 "translations:"
print self.rawTranslations
def parse_translation(self, response):
for sel in response.xpath('//p[not(@class)]'):
rawTranslation = sel.xpath('text()').extract()
rawTranslation = ''.join(rawTranslation)
#print rawTranslation
self.rawTranslations.append(rawTranslation)
#print self.rawTranslations
我的问题是,“打印self.rawTranslations”在parse(...)
方法打印无非"[]"
。这可能意味着以下两种情况之一:它可能是在打印之前重置列表,或者可能在打印parse_translation(...)
的呼叫之前打印,该链接从链接parse(...)
下面的链接填充完列表。我倾向于怀疑它是后者,因为我看不到任何会重置列表的代码,除非课堂体内的"rawTranslations = []"
多次运行。值得注意的是,如果我取消注释parse_translation(...)
中的同一行,它将打印所需的输出,这意味着它正在正确提取文本,并且问题似乎对于主要的parse(...)
方法是唯一的。
我试图解决我认为是一个同步问题的尝试是非常漫无目的 - 我只是尝试使用基于尽可能多Google教程的RLock对象,而且我99%肯定我会滥用它,因为结果是相同的。
我一直在过去的一个小时里搜索互联网,试图更好地理解Python中的锁定,但并没有走得太远。我的想法是在最后一个子页面访问完成后释放锁,但是我发现了很少的语法示例。 – jah