R Web 用 rvest 抓取 coinmarketcap
R Web scraping coinmarketcap with rvest
我正在尝试使用 rvest
-package 从 coinmarketcap.com 获取 table。
解决方法如下图。但是,这个不再起作用了。结果 table 为空。
显然,该网站已以某种方式更改。
谁能提供解决方案?
非常感谢!
library(rvest)
library(tidyverse)
library(xml2)
url<- "https://coinmarketcap.com/currencies/bitcoin/historical-data/"
table <- url %>%
read_html()%>%
html_table() %>%
as.data.frame()
网页现在动态加载。因此,您需要使用 RSelenium
而不仅仅是 rvest
.
这段代码对我有用:
url<- "https://coinmarketcap.com/currencies/bitcoin/historical-data/"
# RSelenium with Firefox
rD <- RSelenium::rsDriver(browser="firefox", port=4546L, verbose=F)
remDr <- rD[["client"]]
remDr$navigate(url)
Sys.sleep(4)
# get the page source
web <- remDr$getPageSource()
web <- xml2::read_html(web[[1]])
table <- html_table(web) %>%
as.data.frame()
# close RSelenium
remDr$close()
gc()
rD$server$stop()
system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)
您不需要浏览器的开销。您可以模仿 API 调用并解析 json 响应。
library(jsonlite)
library(tidyverse)
data <-jsonlite::read_json('https://web-api.coinmarketcap.com/v1/cryptocurrency/ohlcv/historical?id=1&convert=USD&time_start=1614297600&time_end=1619395200')$data$quotes
df <- map_df(data, function(x) {data.frame(x$quote)})
print(df)
# 1614297600 is Fri Feb 26 2021 00:00:00 GMT+0000 for 2021-02-27
# 1619395200 Mon Apr 26 2021 00:00:00 GMT+0000 for 2021-04-25
time_start
和 end_start
是 unix 时间戳,看起来像一天的偏移量,但您需要探索它是如何工作的以及偏移量是否因银行而异 holidays/weekends。
我正在尝试使用 rvest
-package 从 coinmarketcap.com 获取 table。
解决方法如下图。但是,这个不再起作用了。结果 table 为空。 显然,该网站已以某种方式更改。
谁能提供解决方案?
非常感谢!
library(rvest)
library(tidyverse)
library(xml2)
url<- "https://coinmarketcap.com/currencies/bitcoin/historical-data/"
table <- url %>%
read_html()%>%
html_table() %>%
as.data.frame()
网页现在动态加载。因此,您需要使用 RSelenium
而不仅仅是 rvest
.
这段代码对我有用:
url<- "https://coinmarketcap.com/currencies/bitcoin/historical-data/"
# RSelenium with Firefox
rD <- RSelenium::rsDriver(browser="firefox", port=4546L, verbose=F)
remDr <- rD[["client"]]
remDr$navigate(url)
Sys.sleep(4)
# get the page source
web <- remDr$getPageSource()
web <- xml2::read_html(web[[1]])
table <- html_table(web) %>%
as.data.frame()
# close RSelenium
remDr$close()
gc()
rD$server$stop()
system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)
您不需要浏览器的开销。您可以模仿 API 调用并解析 json 响应。
library(jsonlite)
library(tidyverse)
data <-jsonlite::read_json('https://web-api.coinmarketcap.com/v1/cryptocurrency/ohlcv/historical?id=1&convert=USD&time_start=1614297600&time_end=1619395200')$data$quotes
df <- map_df(data, function(x) {data.frame(x$quote)})
print(df)
# 1614297600 is Fri Feb 26 2021 00:00:00 GMT+0000 for 2021-02-27
# 1619395200 Mon Apr 26 2021 00:00:00 GMT+0000 for 2021-04-25
time_start
和 end_start
是 unix 时间戳,看起来像一天的偏移量,但您需要探索它是如何工作的以及偏移量是否因银行而异 holidays/weekends。