gpt4 book ai didi

R:XPath 表达式返回所选元素之外的链接

转载 作者:行者123 更新时间:2023-12-03 15:28:20 27 4
gpt4 key购买 nike

我正在使用 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”的新闻项目的所有链接。

最佳答案

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

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

或者,您可以直接使用 XPath 提取第三个表:
xpathApply(x, "//table[3]//a[contains(@href,'/magazine/') and not(contains(@href, '/recherche/'))]/@href")

关于R:XPath 表达式返回所选元素之外的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16628361/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com