从未使用Scrapy调用回调函数

2024-05-08 14:09:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我是个新手。我已经花了好几个小时试着调试和寻找有用的响应,但我还是被卡住了。我试图从中提取数据www.pro-football-reference.com。这是我现在掌握的密码

import scrapy

from nfl_predictor.items import NflPredictorItem

class NflSpider(scrapy.Spider):
   name = "nfl2"
   allowed_domains = ["http://www.pro-football-reference.com/"]
   start_url = [
    "http://www.pro-football-reference.com/boxscores/201509100nwe.htm"
   ]

    def parse(self, response):
        print "parse"
        for href in response.xpath('// [@id="page_content"]/div[1]/table/tr/td/a/@href'):
        url = response.urljoin(href.extract())
        yield scrapy.Request(url, callback=self.parse_game_content)

    def parse_game_content(self, response):
        print "parse_game_content"
        items = []
        for sel in response.xpath('//table[@id = "team_stats"]/tr'):
            item = NflPredictorItem()
            item['away_stats'] = sel.xpath('td[@align = "center"][1]/text()').extract()
            item['home_stats'] = sel.xpath('td[@align = "center"][2]/text()').extract()
        items.append(item)
    return items

用于调试的parse和I命令

^{pr2}$

我得到以下输出

^{3}$

为什么它会记录我想要的链接的请求,但是它从来没有进入parse_game_content函数来实际获取数据?我还测试了parse_game_content函数作为parse函数,以确保它正在抓取正确的数据,并且在这种情况下能够正常工作。在

谢谢你的帮助!在


Tags: selfcomgameurlparseresponsewwwitems
1条回答
网友
1楼 · 发布于 2024-05-08 14:09:58

默认情况下,parse命令获取给定的URL,并使用处理它的spider来解析它,使用callback选项传递的方法,否则就解析给。在你的情况下,它只解析解析函数。更改命令使 callback如下所示:

scrapy parse  spider=nfl2 "http://www.pro-football-reference.com/boxscores/201509100nwe.htm"  callback=parse_game_content

另外,最好更改parse_game_content函数,如下所示

和13;

和13;

相关问题 更多 >