【问题标题】:scrapy xpath selector works in browser, but not in crawl or shellscrapy xpath 选择器适用于浏览器,但不适用于 crawl 或 shell
【发布时间】:2016-06-15 19:10:30
【问题描述】:

我正在抓取以下页面:http://www.worldfootball.net/all_matches/eng-premier-league-2015-2016/

第一个解析通过,应该得到所有带有分数的链接作为文本。我首先遍历所有匹配行:

for sel in response.xpath('(//table[@class="standard_tabelle"])[1]/tr'):

然后获取表格第6列的链接

    matchHref = sel.xpath('.//td[6]/a/@href').extract()

然而,这不会返回任何内容。我在 Chrome 中尝试了相同的选择器(在 table 和 tr 选择器之间添加了“tbody”),但我得到了结果。但是,如果我在 scrapy shell 中尝试相同的选择器(没有 tbody),我只能从第一个 response.xpath 中获得结果,而以下链接提取则没有。

我以前做过一些这样的循环,但这个简单的事情让我难住了。有没有更好的方法来调试这个?这是一些 shell 输出,我只是尝试简化我的第二个选择,只选择任何 td

In [36]: for sel in response.xpath('(//table[@class="standard_tabelle"])[1]/tr'):
   ....:     sel.xpath('.//td')
   ....:     

什么都没有。想法?

【问题讨论】:

    标签: python xpath scrapy scrapy-spider


    【解决方案1】:

    我要做的是利用第 6 列中的这些链接在 href 属性值中包含 report 的事实。从 shell 演示:

    $ scrapy shell "http://www.worldfootball.net/all_matches/eng-premier-league-2015-2016/"
    >>> for row in response.xpath('(//table[@class="standard_tabelle"])[1]/tr[not(th)]'):
    ...     print(row.xpath(".//a[contains(@href, 'report')]/@href").extract_first())
    ... 
    /report/premier-league-2015-2016-manchester-united-tottenham-hotspur/
    /report/premier-league-2015-2016-afc-bournemouth-aston-villa/
    /report/premier-league-2015-2016-everton-fc-watford-fc/
    ...
    /report/premier-league-2015-2016-stoke-city-west-ham-united/
    /report/premier-league-2015-2016-swansea-city-manchester-city/
    /report/premier-league-2015-2016-watford-fc-sunderland-afc/
    /report/premier-league-2015-2016-west-bromwich-albion-liverpool-fc/
    

    还要注意这部分:tr[not(th)] - 这有助于跳过没有相关链接的标题行。

    【讨论】:

    • 太棒了。我已经注意到了 not(th) 选择器!通过查看scrapy 的文档,我不知道这样的选择器是可能的。我以前写过这样的东西来解决这些问题:thRow = sel.xpath('./th') if thRow: return 非常感谢
    • 为什么会这样,如果我在没有print 的情况下执行第一个选择器response.xpath,shell 会显示结果。但是在 for 循环中使用第二个选择器,它只打印前面带有“打印”的结果?
    • @willdanceforfun 不完全确定您在描述什么,您能否详细说明(如果有意义的话,可能在单独的问题中......)?谢谢。
    • 我在这里提出了这个问题:stackoverflow.com/questions/35790211/…
    猜你喜欢
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多