【问题标题】:Scraping table using html_table in R在 R 中使用 html_table 抓取表格
【发布时间】:2018-05-10 04:12:47
【问题描述】:

我想从以下链接中获取行业权重表:

http://portfolios.morningstar.com/fund/summary?t=SPY&region=usa&culture=en-US&ownerCountry=USA

我想要的表格是网站源代码中的表格 6。我有以下用 R 编写的脚本:

 library(rvest)
 turl = 'http://portfolios.morningstar.com/fund/summary?t=SPY'
 turlr = read_html(turl) 
 df6<-html_table(html_nodes(turlr, 'table')[[6]], fill = TRUE) 

但是,当我运行脚本的最后一行时,我收到以下错误消息

out[j + k, ] 中的错误:下标超出范围

【问题讨论】:

  • 正是您没有包含导致此错误的重要代码
  • 您的目标表中有嵌入的图表和分组。在html_table 接受之前,您需要更改返回的节点。请参阅this question 以获得一些指导。
  • 在 SO 上几乎有无数的 R + 抓取 + 晨星帖子。哪些没有可以帮助您的信息?我一直对此感到困惑,因为创建 q 比进行实际搜索需要更多的精力。

标签: r web-scraping html-table html-parsing rvest


【解决方案1】:

由于所需表格的设计方式不同,rvest 无法将其格式化为正确的表格。但是使用XML 包你可以很容易地做到这一点。

library(XML)
library(dplyr)

#read required table
turl = 'http://portfolios.morningstar.com/fund/summary?t=SPY'
temp_table <- readHTMLTable(turl)[[6]]

#process table to readable format
final_table <- temp_table %>%
  select(V2, V3, V4, V5) %>%
  na.omit() %>%
  `colnames<-` (c("","% Stocks","Benchmark","Category Avg")) %>%
  `rownames<-` (seq_len(nrow(.)))
final_table

输出是:

                          % Stocks Benchmark Category Avg
1                Cyclical                                
2         Basic Materials     2.79      3.16         3.22
3       Consumer Cyclical    11.06     11.42        11.15
4      Financial Services    16.39     16.50        17.22
5             Real Estate     2.24      3.18         2.00
6               Sensitive                                
7  Communication Services     3.56      3.37         3.50
8                  Energy     5.83      5.79         5.79
9             Industrials    10.37     10.89        11.70
10             Technology    22.16     21.41        19.72
11              Defensive                                
12     Consumer Defensive     8.20      7.60         8.56
13             Healthcare    14.24     13.57        14.57
14              Utilities     3.15      3.11         2.59

希望对你有帮助!

【讨论】:

  • 这很棒。非常感谢!
猜你喜欢
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 2018-06-27
  • 2022-01-12
相关资源
最近更新 更多