首页 > 解决方案 > rvest 是从该表中收集信息的最佳工具吗?

问题描述

我使用 rvest 包来提取公司列表和a.href每个公司中的元素,我需要继续进行数据收集过程。这是网站的链接:http ://www.bursamalaysia.com/market/listed-companies/list-of-companies/main-market 。

我已经使用以下代码来提取表格,但没有任何结果。我使用了其他方法,如“Scraping table of NBA stats with rvest”和类似链接中发布的方法,但我无法获得我想要的。任何帮助将不胜感激。

我的代码:

link.main <- 
 "http://www.bursamalaysia.com/market/listed-companies/list-of-companies/main-market/"

web <- read_html(link.main) %>% 
html_nodes("table#bm_equities_prices_table") 
    # it does not work even when I write html_nodes("table") 
    or ".table" or #bm_equities_prices_table

web <- read_html(link.main) 
        %>% html_nodes(".bm_center.bm_dataTable") 
  # no working

web <- link.main %>% read_html() %>% html_table() 
  # to inspect the position of table in this website 

标签: cssrdynamicweb-scrapingrvest

解决方案


该页面使用 JavaScript 生成表格,因此您需要使用RSelenium或 Python 的 Beautiful Soup 来模拟浏览器会话并允许 javascript 运行。

另一种选择是使用 @hrbrmstr 的 Awesome 包decapitated,它基本上在后台运行无头 Chrome 浏览器会话。

#devtools::install_github("hrbrmstr/decapitated")

library(decapitated)
library(rvest)

res <- chrome_read_html(link.main)

main_df <- res %>% 
  rvest::html_table() %>%
  .[[1]] %>%
  as_tibble()

这样就可以输出表格的内容了。如果您想获取表格下的元素(href表格文本后面的属性),您需要做更多的列表体操。表格中的一些元素实际上是缺少链接,通过 css 提取被证明是困难的。

library(dplyr)
library(purrr)

href_lst <- res %>% 
  html_nodes("table td") %>% 
  as_list() %>% 
  map("a") %>% 
  map(~attr(.x, "href"))

# we need every third element starting from second element
idx <- seq.int(from=2, by=3, length.out = nrow(main_df))

href_df <- tibble(
  market_href=as.character(href_lst[idx]),
  company_href=as.character(href_lst[idx+1])
)

bind_cols(main_df, href_df)

#> # A tibble: 800 x 5
#>       No `Company Name`   `Company Website` market_href   company_href
#>    <int> <chr>            <chr>             <chr>         <chr>       
#>  1     1 7-ELEVEN MALAYS~ http://www.7elev~ /market/list~ http://www.~
#>  2     2 A-RANK BERHAD [~ http://www.arank~ /market/list~ http://www.~
#>  3     3 ABLEGROUP BERHA~ http://www.gefun~ /market/list~ http://www.~
#>  4     4 ABM FUJIYA BERH~ http://www.abmfu~ /market/list~ http://www.~
#>  5     5 ACME HOLDINGS B~ http://www.suppo~ /market/list~ http://www.~
#>  6     6 ACOUSTECH BERHA~ http://www.acous~ /market/list~ http://www.~
#>  7     7 ADVANCE SYNERGY~ http://www.asb.c~ /market/list~ http://www.~
#>  8     8 ADVANCECON HOLD~ http://www.advan~ /market/list~ http://www.~
#>  9     9 ADVANCED PACKAG~ http://www.advan~ /market/list~ http://www.~
#> 10    10 ADVENTA BERHAD ~ http://www.adven~ /market/list~ http://www.~
#> # ... with 790 more rows

推荐阅读