首页 > 解决方案 > 无法抓取 html 表格 rvest

问题描述

尝试使用 rvest 将https://www.cefconnect.com/closed-end-funds-daily-pricing 抓取到 R 数据框中。继续尝试各种 css 和 xpath 选择器,但无法收集主数据表。

使用了 'table'、'tbody'、'td' 和 'tr xpath 选择器但没有成功。两列是超链接,其余是静态文本。

URL <- 'https://www.cefconnect.com/closed-end-funds-daily-pricing'
html <- read_html(URL)

html2 <- html %>%
html_nodes(xpath = '//table') %>% 
html_nodes(xpath = '//td/a[1]/text()') %>%
html_text()
html3 <- as.data.frame(html2)

标签: cssxpathweb-scrapingrvest

解决方案


尝试分析在浏览器中加载网站时处理的请求。这可以通过在 Chrome 浏览器中浏览以下内容来完成。

设置 >> 更多工具 >> 开发者工具(快捷键:Ctrl + Shift + I)

执行此操作时,您可以看到如下请求之一 https://www.cefconnect.com/api/v3/DailyPricing?props=Ticker,Name,DistributionRateNAV,LastUpdated,Discount,DistributionRatePrice,ReturnOnNAV,CategoryId,Cat​​egoryName, IsManagedDistribution,Price,PriceChange,NAV,NAVPublished,Cusip/&_=1546832481302

如果您单击上面的链接,您将看到以 JSON 格式显示在表格中的数据。这是您需要转换为数据框的内容。

url<-"https://www.cefconnect.com/api/v3/DailyPricing?props=Ticker,Name,DistributionRateNAV,LastUpdated,Discount,DistributionRatePrice,ReturnOnNAV,CategoryId,CategoryName,IsManagedDistribution,Price,PriceChange,NAV,NAVPublished,Cusip/&_=1546832481302"


library(rvest)
page<-html_session(url)
json<-readBin(page$response$content, what="json")

library(jsonlite)
df<-fromJSON(json)

推荐阅读