gpt4 book ai didi

r - 通过xpath的rvest空列表表

转载 作者:行者123 更新时间:2023-12-03 17:22:29 25 4
gpt4 key购买 nike

我需要帮助从下面的网站上抓取数据。我复制了此处链接https://msperlin.github.io/pafdR/importingInternet.html#accessing-data-from-web-pages-webscraping的方式,以降低费率表,但仅得到列表0。有人可以帮我吗?

library(rvest)

# set url and xpath
my.url <- 'https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield'
my.xpath <- '//*[@id="t-content-main-content"]/div/table/tbody/tr/td/div/table'


# get nodes from html
out.nodes <- html_nodes(read_html(my.url),
xpath = my.xpath)

# get table from nodes (each element in
# list is a table)
df <- html_table(out.nodes)
df

最佳答案

通常最好不要使用非常精确的XPath语句,因为页面的结构可能会更改,并且有时在浏览器源代码或Developer Tools中看起来正确的东西(浏览器在读取HTML时会修改HTML)。

使用上述开发人员工具(在这种情况下通过Firefox,但Chrome也可以正常工作),表格附近的检查元素显示:

enter image description here

我们可以坚持使用CSS选择器语法并执行以下操作:

library(rvest)

pg <- read_html("https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield")

html_node(pg, "table.t-chart") %>%
html_table()
## Date 1 mo 3 mo 6 mo 1 yr 2 yr 3 yr 5 yr 7 yr 10 yr 20 yr 30 yr
## 1 10/01/18 2.13 2.23 2.40 2.60 2.82 2.90 2.96 3.04 3.09 3.18 3.24
## 2 10/02/18 2.14 2.23 2.41 2.61 2.82 2.88 2.94 3.01 3.05 3.14 3.20
## 3 10/03/18 2.15 2.23 2.41 2.62 2.85 2.94 3.02 3.10 3.15 3.24 3.30
## 4 10/04/18 2.16 2.22 2.42 2.63 2.87 2.97 3.05 3.14 3.19 3.29 3.35
## 5 10/05/18 2.15 2.23 2.41 2.64 2.88 2.99 3.07 3.18 3.23 3.34 3.40


在这种情况下,CSS选择器更容易使用(并非总是如此),但是您也可以使用XPath查询:

html_node(pg, xpath = ".//table[@class='t-chart']")

关于r - 通过xpath的rvest空列表表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52685569/

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