css - 无法抓取 html 表 rvest

标签 css xpath web-scraping rvest

试图抓取 https://www.cefconnect.com/closed-end-funds-daily-pricing 使用 rvest 进入 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)

最佳答案

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

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

在这样做时,您可以看到其中一个请求如下 https://www.cefconnect.com/api/v3/DailyPricing?props=Ticker,Name,DistributionRateNAV,LastUpdated,Discount,DistributionRatePrice,ReturnOnNAV,CategoryId,CategoryName,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)

关于css - 无法抓取 html 表 rvest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54066146/

相关文章:

java - 如何在没有 DOM 的情况下在 java 中读取 XML?

c# - 一个 XmlDataProvider WPF 的多个 XPath

python - 在广泛的 Scrapy Web 爬虫中只允许内部链接

css - JSF CSS panelGrid - 如何使其包含的元素都保持恒定宽度

html - 何时使用 CSS + 符号

html - HTML建议:我应该选择调整图库图像的大小还是使用单独的缩略图图像?

javascript - jQuery 多个加/减计数器

xml - 具有相同 namespace 名称、不同 URI 的 XML 的 XSLT

html - 在 R 中使用 `read_html` 使用 `rvest` 时缺少元素

python - 加快 Selenium 中的网络抓取速度