class XMLDocumentContent 对象的 Xpath 错误

Xpath error with object of class XMLDocumentContent

我刚开始使用 RCurl 包,在阅读了 xpath 的基础知识后,我试图解决一个简单的例子。我想要做的是从本地体育网站检索所有表格。我使用了以下代码:

# used packages
library(Rcurl)
library(XML)

# retrieve
test <- getURL(url = "http://sporza.be/cm/sporza/voetbal/Jupiler_Pro_League")

# parse
test <- htmlTreeParse(test)

# select tables
tabel <- xpathApply(test, "//table", xmlValue)

当我运行这段代码时总是遇到如下错误:

Error in UseMethod("xpathApply") : 
no applicable method for 'xpathApply' applied to an object of class "XMLDocumentContent"

我似乎缺少一些非常基本的东西,但我似乎看不出到底是什么。

xpathApply 不适用于 XMLDocumentContent 对象,但适用于 XMLNodes。您可以使用 xmlRoot 提取 xml 文档的根节点,然后对该对象进行 xpath 查询

table <- xpathApply(xmlRoot(test), "//table", xmlValue)

解决方案 1

library(rvest)
all_table1<-"http://sporza.be/cm/sporza/voetbal/Jupiler_Pro_League" %>%
            html%>%
            html_table()

解决方案 2

library(XML)
all_table2<-readHTMLTable(htmlParse("http://sporza.be/cm/sporza/voetbal/Jupiler_Pro_League"))