我正在使用R来使用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))
Run Code Online (Sandbox Code Playgroud)
如果查看输出,最后的链接不是来自主表,而是来自侧边栏,即使我在第三行中选择了主表,要求对象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)
Run Code Online (Sandbox Code Playgroud)
这将在此网站上保存所有带有关键字"Hadopi"的新闻项的链接.
.如果要将搜索限制在当前节点,则
需要以 开始模式。/返回到文档的开头(即使根节点不在 中y)。
xpathSApply(y, ".//a/@href" )
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用 XPath 直接提取第三个表:
xpathApply(x, "//table[3]//a[contains(@href,'/magazine/') and not(contains(@href, '/recherche/'))]/@href")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
494 次 |
| 最近记录: |