Scrapy:修改抓取网页的规则

时间:2014-03-09 23:37:55

标签: javascript python regex scrapy

我已经开始使用scrapy进行我的一个项目来从网球网站上搜集数据。 Here是我要删除数据的示例页面。如你所见,我想为网球运动员搜索数据。我需要以递归方式浏览整个页面并收集“匹配统计数据”(Theres一个名为“匹配统计数据”的链接,每个匹配),以便玩家的比赛。我已经编写了代码来解析打开的匹配统计信息弹出窗口中的数据。我现在需要做的就是通过最初的蜘蛛打开这些匹配统计页面。

在我读过的所有示例中,我们可以编写规则来将scrapy导航到需要抓取的不同网址。在我的情况下,我只想写一个规则到不同的匹配统计链接。但是,如果您看到我要抓取的页面,“匹配统计信息”链接的格式如下:javascript:makePopup('match_stats_popup.php?matchID=183704502')。正如我在网上看到的那样(我可能错了!),scrapy无法处理javascript,因此无法“点击”该链接。但是,由于链接是javascript弹出窗口,因此可以将链接的match_stats_popup.php?matchID=183704502部分添加到主URL以获取标准html页面:

http://www.tennisinsight.com/match_stats_popup.php?matchID=183704502

我希望我可以在抓取之前修改规则。总之,我只是想找到类型为javascript:makePopup('match_stats_popup.php?matchID=183704502的链接,并修改它们,使它们现在属于http://www.tennisinsight.com/match_stats_popup.php?matchID=183704502

类型

这是我到目前为止在规则中写的,它没有打开任何页面:

rules = (
    Rule(SgmlLinkExtractor(allow='/match_stats_popup.php?matchID=\d+'),
        'parse_match', follow=True,
    ),
)

parse_match是解析打开的匹配统计信息弹出窗口中的数据的方法。

希望我的问题足够清楚!

1 个答案:

答案 0 :(得分:0)

使用BaseSgmlLinkExtractorSgmlLinkExtractor,您可以指定要从中提取的标记和用于提取链接的process_value函数。官方文档中有nice example。以下是您的示例代码:

class GetStatsSpider(CrawlSpider):
    name = 'GetStats'
    allowed_domains = ['tennisinsight.com']
    start_urls = ['http://www.tennisinsight.com/player_activity.php?player_id=1']

    def getPopLink(value):
        m = re.search("javascript:makePopup\('(.+?)'\)", value)
        if m:
            return m.group(1)

    rules = (
            Rule(SgmlLinkExtractor(allow=r"match_stats_popup.php\?matchID=\d+",
                restrict_xpaths='//td[@class="matchStyle"]',
                tags='a', attrs='href', process_value=getPopLink), callback='parse_item', follow=True),
            )

    def parse_item(self, response):
        sel = Selector(response)
        i = TennisItem()
        i['url_stats'] = response.url
        return i
相关问题