【问题标题】:How to select the first n elements in XPath如何选择 XPath 中的前 n 个元素
【发布时间】:2014-10-06 17:35:50
【问题描述】:

我正在使用 YQL 从网站上抓取一些图像。

问题是我只想要该网站的前 5 张图片。

我有以下疑问:

select * from html where url="http://myanimelist.net/anime/9253/Steins;Gate" and xpath='//img[position()<=5]'

但是,它返回的是所有图像元素,而不是前 5 个。

YQL 控制台:open YQL console with above XPath

我的 XPath 查询有什么问题吗?

PS:我不能使用LIMIT 5,因为我可能还需要刮掉一些其他标签。

【问题讨论】:

    标签: html xml xpath web-scraping yql


    【解决方案1】:

    此 XPath 表达式将选择前 5 个 img 元素:

    //img[count(preceding::img) < 5]
    

    这是整个 YQL 查询:

    select * from html where url="http://myanimelist.net/anime/9253/Steins;Gate" and xpath='//img[count(preceding::img) < 5]'
    

    您可以在YQL Console 上观看它。

    【讨论】:

    • 哇,前面有一个巧妙的小技巧。我知道我必须以某种方式使用count(),但我尝试使用self 而不是preceding
    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 2010-10-02
    • 2011-10-07
    • 2014-09-14
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 2018-02-21
    相关资源
    最近更新 更多