css - 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
解决方案
该页面使用 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
推荐阅读
- c# - C++/CLI 混合托管/本机 DLL 不起作用
- javascript - JS将数组的值添加到对象
- java - 如何将 Long 列表发送到休息控制器 Spring Boot
- kubernetes - 从 Kubernetes pod/容器内部识别节点的区域
- php - 如何通过 AJAX 运行 SQL 选择查询(实时结果)
- python - Python Top 胜过
- java - 在 shell 脚本中的 oracle DB 上的 execute.sql 文件
- html - css 对包含标签的 p 标签进行分词
- php - 最小化 GitHub 上传 codeigniter 框架
- javascript - Angular 应用程序未在 Edge 中打开它重定向到在 IE 11 中自动打开