使用右标记(class、div、span、table 等)在 R 中使用 rvest

Using Right Tag (class, div, span, table, etc.) Using rvest in R

我已经开始使用 rvest 包并遇到了一些一致的问题,即如何引用 HTML 代码。

例如下面的代码return是一个空字符(最终要0.74)。基本上我唯一能得到 return 的是使用“div”作为节点,它只是 return 的所有文本。 “tr.total-return”,“总计-return”,“div.sal-trailing-return__middle”全部return也为空。

a=read_html(https://www.morningstar.com/funds/xnas/hcyix/performance)
b=html_nodes(a, "td")

该页面动态加载。因此,您需要使用 RSelenium,而不仅仅是 rvest.

这段代码对我有用,可以获取0.74的数据点。

library(rvest)
library(tidyverse)
library(RSelenium)

url<- "https://www.morningstar.com/funds/xnas/hcyix/performance"

# RSelenium with Firefox
rD <- RSelenium::rsDriver(browser="firefox", port=4546L, verbose=F)
remDr <- rD[["client"]]
remDr$navigate(url)
Sys.sleep(4)

# get the page source
web <- remDr$getPageSource()
web <- xml2::read_html(web[[1]])

b <- html_node(web, ".total-return > td:nth-child(1)") %>%
  html_text() %>%
  trimws()

# close RSelenium
remDr$close()
gc()
rD$server$stop()
system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)