【问题标题】:R: XPath expression returns links outside of selected elementR:XPath 表达式返回所选元素之外的链接
【发布时间】:2013-05-19 05:06:15
【问题描述】:

我正在使用 R 从 that page 的主表中抓取链接,使用 XPath 语法。主表是页面上的第三个,我只想要包含杂志文章的链接。

我的代码如下:

require(XML)
(x = htmlParse("http://www.numerama.com/magazine/recherche/125/hadopi/date"))
(y = xpathApply(x, "//table")[[3]])
(z = xpathApply(y, "//table//a[contains(@href,'/magazine/') and not(contains(@href, '/recherche/'))]/@href"))
(links = unique(z))

如果您查看输出,即使我在第三行通过询问对象y 仅包含第三个表来选择主表,最终链接也不是来自主表,而是来自侧边栏。

我做错了什么?使用 XPath 进行编码的正确/更有效的方法是什么?

注意:XPath新手写法。

已答复(很快),非常感谢!我的解决方案如下。

extract <- function(x) {
    message(x)
    html = htmlParse(paste0("http://www.numerama.com/magazine/recherche/", x, "/hadopi/date"))
    html = xpathApply(html, "//table")[[3]]
    html = xpathApply(html, ".//a[contains(@href,'/magazine/') and not(contains(@href, '/recherche/'))]/@href")
    html = gsub("#ac_newscomment", "", html)
    html = unique(html)
}

d = lapply(1:125, extract)
d = unlist(d)
write.table(d, "numerama.hadopi.news.txt", row.names = FALSE)

这会保存本网站上所有带有关键字“Hadopi”的新闻项目的链接。

【问题讨论】:

    标签: r xpath


    【解决方案1】:

    如果要将搜索限制在当前节点,则需要以 . 开头的模式。 / 回到文档的开头(即使根节点不在y 中)。

    xpathSApply(y, ".//a/@href" )
    

    或者,您可以直接使用 XPath 提取第三个表:

    xpathApply(x, "//table[3]//a[contains(@href,'/magazine/') and not(contains(@href, '/recherche/'))]/@href")
    

    【讨论】:

      猜你喜欢
      • 2019-11-10
      • 1970-01-01
      • 2017-04-26
      • 2011-07-06
      • 1970-01-01
      • 2020-12-17
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多