【问题标题】:Scrapy: Modify rules for scraping web pageScrapy:修改网页抓取规则
【发布时间】:2014-04-12 22:34:52
【问题描述】:

我已经开始在我的一个项目中使用 scrapy 从网球网站上抓取数据。 Here 是我想刮掉数据的示例页面。如您所见,我想为一名网球运动员抓取数据。我需要递归地浏览整个页面并为玩家的比赛收集“比赛统计数据”(每场比赛旁边都有一个标题为“比赛统计数据”的链接)。我已经编写了代码来解析打开的匹配统计信息弹出窗口中的数据。我现在需要做的就是通过初始蜘蛛打开这些比赛统计页面。

在我阅读过的所有示例中,我们可以编写规则来将 scrapy 导航到需要抓取的不同 url。就我而言,我只想为不同的比赛统计链接写一条规则。但是,如果您看到我要抓取的页面,“比赛统计”链接的格式如下: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 是从打开的比赛统计弹出窗口中解析数据的方法。

希望我的问题足够清楚!

【问题讨论】:

  • 当我点击您的链接时,我只看到一个“比赛统计”可供点击。
  • 嗨! tennisinsight.com/player_activity.php?player_id=1 主链接 :) 有玩家的比赛历史记录,每场比赛都有对应的 MatchStats 链接,会弹出一个弹窗

标签: javascript python regex scrapy


【解决方案1】:

使用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

【讨论】:

  • 感谢您的回复。这是网址:tennisinsight.com/player_activity.php?player_id=1 它有一个带有比赛统计链接的比赛列表。根据您提供的链接(谢谢!),代码是否如下所示:
  • m = re.search("javascript:makePopup('match_stats_popup.php?matchID=\d+')", value) m.group[1] 在示例中指的是什么? :)
猜你喜欢
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
相关资源
最近更新 更多