【问题标题】:How do I get extract a table from an HTML Page as a data.frame using XML and Rcurl in R [closed]如何在 R 中使用 XML 和 Rcurl 从 HTML 页面中提取表格作为 data.frame [关闭]
【发布时间】:2018-04-21 19:22:18
【问题描述】:

我需要从以下 HTML 页面中提取一个表格作为 data.frame:

https://www.forbes.com/powerful-brands/list/#tab:rank.html

【问题讨论】:

  • 请帮忙.....

标签: html r xml rcurl


【解决方案1】:

该表具有实时内容,因此您需要一个无头浏览器,Rselenium 应该是您的首选。此外,您需要 rvest 来提取表格

注意:导航到该页面后,会有一个过渡页面,您可以手动单击继续或等待几秒钟。

代码:

library(rvest)
library(RSelenium)

remDr <-rsDriver(port = 4445L,browser = "chrome")
myclient <- remDr$client
#navigate to that page
#After navigate to that page,you need to manually click "continue button" or select and click it with css or just wait a few seconds
myclient$navigate("https://www.forbes.com/powerful-brands/list/#tab:rank")
#you need to scroll down several times, or you will get only top 10 in the list
replicate(20,myclient$sendKeysToActiveElement(list(key="page_down")))
#get pagesource
mypagesource <- unlist(myclient$getPageSource())
#Using rvest to extract table
mytable <-read_html(mypagesource) %>% html_node("#the_list") %>% html_table()


> str(mytable)
'data.frame':   109 obs. of  8 variables:
    $                    : logi  NA NA NA NA NA NA ...
$ Rank               : chr  "#1" "#2" "#3" "#4" ...
$ Brand              : chr  "Apple" "Google" "Microsoft" "Facebook" ...
$ Brand Value        : chr  "$170 B" "$101.8 B" "$87 B" "$73.5 B" ...
$ 1-Yr Value Change  : chr  "10%" "23%" "16%" "40%" ...
$ Brand Revenue      : chr  "$214.2 B" "$80.5 B" "$85.3 B" "$25.6 B" ...
$ Company Advertising: chr  "$1.8 B" "$3.9 B" "$1.6 B" "$310 M" ...
$ Industry           : chr  "Technology" "Technology" "Technology" "Technology" ...

然后您可以在之后清理数据:

这些包的介绍和教程:
https://cran.r-project.org/web/packages/RSelenium/vignettes/RSelenium-basics.html
https://stat4701.github.io/edav/2015/04/02/rvest_tutorial/

【讨论】:

  • 非常感谢。代码就像一个魅力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
  • 2013-03-09
  • 2014-07-21
  • 2015-02-02
  • 1970-01-01
  • 2021-04-06
相关资源
最近更新 更多