【发布时间】:2019-10-28 14:18:24
【问题描述】:
我有一个简单的蜘蛛类,它有两个功能。一个从起始页面获取链接并输入它们(也 - 获取下一页链接),另一个 - 解析每个链接(它指向的页面)。问题是我有一个 for 循环,它遍历链接并为每个链接生成一个 scrapy.Request,在这个 for 循环之后,我有一个 if 语句来检查当前页面是否是最后一个,如果不是 - - 我想产生带有下一页链接的第一个功能,如果是的话 - 停止蜘蛛并说“最后一页,伙计!”。
def parse(self, response):
links = response.xpath('//tags_to_be_chosen/@href').getall()
next_page = response.xpath('//tag_to_be_chosen/@href').get()
check = response.xpath('//tag_to_be_chosen/text()').get()
for link in links:
yield scrapy.Request(response.urljoin(link.strip()), callback=self.parse_page)
if 'specific_string_is' in check: # go to next page, but only after for loop has finished its job
yield scrapy.Request(response.urljoin(next_page.strip()), callback=self.parse)
else: # stop the crawler, because we've reached the last page
print('We\'ve reached the last page!')
def parse_page(self, response):
with open('file_to_write', 'a') as file: # when there's a table of items to be crawled (different tags used than for a single item)
for item in response.xpath('//tags_to_be_chosen/text()').getall():
file.write('{}\n'.format(item.strip()))
else: # when there's a single item to be crawled (different tag used than for multiple items
item = response.xpath('//tag_to_be_chosen').get()
item = item.strip()
item = re.sub('sth_to_be_deleted', '', item)
file.write('{}\n'.format(item))
预期的结果是等到for循环完成调用第2个函数(输入并解析所有链接),然后才输入下一页链接。出于某种原因,if 正在检查,而for 仍在循环链接,正在调用解析下一页的函数(这意味着更改链接),并且该过程开始于未完成“旧”链接的新链接。
如 cmets 中所指出的,已完成大编辑:
【问题讨论】:
-
您说“出于某种原因(可能就是这样),如果在 for 仍在循环链接时正在检查 if ”。我认为这是不可能的,除非
parse被多次调用,在这种情况下,可能其中一个调用在loop中,而另一个调用已经到达if语句。
标签: python function for-loop scrapy