gpt4 book ai didi

python - 多页 scrapy 生成我的项目太快而无法完成 - 功能未链接并等待完成

转载 作者:太空宇宙 更新时间:2023-11-03 16:53:32 25 4
gpt4 key购买 nike

我正在制作一个足球应用程序,试图让我了解多页面抓取的工作原理。

例如,在第一页 ( http://footballdatabase.com/ranking/world/1 ) 上有 2 组我想要抓取的链接:俱乐部名称链接和分页链接

我想浏览a)每一页(分页),然后b)浏览每个俱乐部并获取其当前的欧盟排名。

我写的代码在某种程度上是有效的。然而,我最终只得到了大约 45 个结果,而不是 2000 多个俱乐部。 --注:分页数为45页。因此,一旦循环完成,一切就完成了,我的元素就生成了。

如何将所有内容链接在一起,以便最终得到 2000 多个结果?

这是我的代码

# get Pagination links
def parse(self, response):
for href in response.css("ul.pagination > li > a::attr('href')"):
url = response.urljoin(href.extract())
yield scrapy.Request(url, callback=self.parse_club)

# get club links on each of the pagination pages
def parse_club(self, response):


# loop through each of the rows
for sel in response.xpath('//table/tbody/tr'):

item = rankingItem()

item['name'] = sel.xpath('td/a/div[@class="limittext"]/text()').extract()

# get more club information
club_href = sel.xpath('td[2]/a[1]/@href').extract_first()
club_url = response.urljoin(club_href)
request = scrapy.Request(club_url,callback=self.parse_club_page_2)

request.meta['item'] = item
return request

# get the EU ranking on each of the club pages
def parse_club_page_2(self,response):

item = response.meta['item']
item['eu_ranking'] = response.xpath('//a[@class="label label-default"][2]/text()').extract()

yield item

最佳答案

您需要从 parse_club 回调中yield - 而不是return:

# get club links on each of the pagination pages
def parse_club(self, response):
# loop through each of the rows
for sel in response.xpath('//table/tbody/tr'):
item = rankingItem()
item['name'] = sel.xpath('td/a/div[@class="limittext"]/text()').extract()

# get more club information
club_href = sel.xpath('td[2]/a[1]/@href').extract_first()
club_url = response.urljoin(club_href)
request = scrapy.Request(club_url,callback=self.parse_club_page_2)

request.meta['item'] = item
yield request # FIX HERE
<小时/>

我还将元素定位部分简化为:

def parse_club(self, response):
# loop through each of the rows
for sel in response.css('td.club'):
item = rankingItem()
item['name'] = sel.xpath('.//div[@itemprop="itemListElement"]/text()').extract_first()

# get more club information
club_href = sel.xpath('.//a/@href').extract_first()
club_url = response.urljoin(club_href)
request = scrapy.Request(club_url, callback=self.parse_club_page_2)

request.meta['item'] = item
yield request

关于python - 多页 scrapy 生成我的项目太快而无法完成 - 功能未链接并等待完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35655305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com