gpt4 book ai didi

r - htmltab 找不到使用数字或字符向量作为 'which' 参数的表格

转载 作者:行者123 更新时间:2023-12-04 10:50:36 27 4
gpt4 key购买 nike

我正在尝试使用 htmltab 将一些表格从美联储网站抓取到 RStudio。

此代码适用于一个表,使用 1 的数字向量作为表的 rank 'which' 参数:

url <- 'https://www.federalreserve.gov/releases/h6/current/default.htm'
df1 <- htmltab(url,1)

然而,另一个表似乎不接受 'which' 参数的数字向量。
url <- 'https://www.federalreserve.gov/monetarypolicy/bst_recenttrends_accessible.htm'
df2 <- htmltab(url,1)

输出:

Error: Couldn't find the table. Try passing (a different) information to the which argument.



htmltab 的 R 文档提到使用将表的 XPath 描述为 'which' 参数的字符向量,但我似乎也无法使其正常工作:
url <- 'https://www.federalreserve.gov/monetarypolicy/bst_recenttrends_accessible.htm'
xp <- '//*[@id="bstContainer"]/table[1]'
df2 <- htmltab(url, xp)

输出:

Error in Node[1] : subscript out of bounds



谁能看到我在这张 table 上哪里出错了?

最佳答案

您的代码不起作用的原因是您只能使用您的方法抓取静态 html。第二个页面将数据动态加载到其表中,因此该表实际上并不存在于您下载到 R 的页面中。幸运的是,通过指向 xhr 请求使用的底层 xml 的链接可以直接获取数据。将其读入数据帧也很简单。

require("xml2")
page <- read_html("https://www.federalreserve.gov/data.xml")
tables <- xml_find_all(page,"//series")
first_table <- data.frame(date = xml_attr(xml_contents(tables[[1]]), "index"),
amount = xml_attr(xml_contents(tables[[1]]), "value"))

# > first_table
# > date amount
# > 1 1-Aug-07 870261.00
# > 2 8-Aug-07 865453.00
# > 3 15-Aug-07 864931.00
# > 4 22-Aug-07 862775.00
# > 5 29-Aug-07 872873.00
# > 6 5-Sep-07 871156.00
# > 7 12-Sep-07 886314.00
# > 8 19-Sep-07 867732.00
# > 9 26-Sep-07 889900.00
# > 10 3-Oct-07 869051.00
#...

关于r - htmltab 找不到使用数字或字符向量作为 'which' 参数的表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59490401/

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