是否可以從使用生成的檔案中刮取 adatatable或嵌入.csv檔案的內容?例如使用檔案中的選項。.htmlknitrDT::datatable()buttons = c('csv').Rmd
我的第一種方法是使用rvest(例如rvest::read_html(x = 'example.html') %>% rvest::html_table()),但它沒有找到任何表格,我認為這是因為datatable不使用 html 表格元素來顯示資料。
下面是一個.Rmd檔案的最小示例,我從中編織了一個“.html”檔案,其中包括兩個我想抓取的資料表。
例子.Rmd
---
title: "Example for scraping"
output: html_document
---
# Example 1
```{r}
tbl1 <- mtcars[1:20, 1:4]
DT::datatable(tbl1, extensions = 'Buttons', options = list(dom = 'Blfrtip',buttons = c('csv'),paging=FALSE))
```
# Example 2
```{r}
tbl2 <- mtcars[21:32, 7:11]
DT::datatable(tbl2, extensions = 'Buttons', options = list(dom = 'Blfrtip',buttons = c('csv'),paging=FALSE))
```
這可以在 RStudio 中編織,也可以使用 編織rmarkdown::render(input = 'example.Rmd'),導致example.html我想從中刮掉。
謝謝!
uj5u.com熱心網友回復:
htmlwidgets呈現為的htmltables,將資料存盤為 JSON ,您可以訪問并使用它來重建資料幀。通過這種方式,您還可以繞過分頁的各種設定。我在下面制作了這種方法的說明性示例:
library(tidyverse)
library(rvest)
library(jsonlite)
# Get the JSON that is used to create the table
json_data <-
read_html("example.html") |>
html_elements(css = "#example-1") |>
html_elements("script") |>
html_text() |>
jsonlite::fromJSON()
# Extract data and reshape it
table <-
json_data$x[["data"]] |>
as_tibble() |>
t() |>
as_tibble()
# Extract variable names from html stored in the json
variable_names <-
minimal_html(json_data$x[["container"]]) |>
html_table() %>%
.[[1]] |>
colnames()
# Add the correct column names
colnames(table) <- variable_names
table
輸出:
# A tibble: 20 × 5
`` mpg cyl disp hp
<chr> <chr> <chr> <chr> <chr>
1 Mazda RX4 21 6 160 110
2 Mazda RX4 Wag 21 6 160 110
3 Datsun 710 22.8 4 108 93
4 Hornet 4 Drive 21.4 6 258 110
5 Hornet Sportabout 18.7 8 360 175
6 Valiant 18.1 6 225 105
7 Duster 360 14.3 8 360 245
8 Merc 240D 24.4 4 146.7 62
9 Merc 230 22.8 4 140.8 95
10 Merc 280 19.2 6 167.6 123
11 Merc 280C 17.8 6 167.6 123
12 Merc 450SE 16.4 8 275.8 180
13 Merc 450SL 17.3 8 275.8 180
14 Merc 450SLC 15.2 8 275.8 180
15 Cadillac Fleetwood 10.4 8 472 205
16 Lincoln Continental 10.4 8 460 215
17 Chrysler Imperial 14.7 8 440 230
18 Fiat 128 32.4 4 78.7 66
19 Honda Civic 30.4 4 75.7 52
20 Toyota Corolla 33.9 4 71.1 65
更新。 一種使用相同方法獲取所有表的方法,即不是最漂亮的代碼:
# Get the html of the the scripts
html_data <-
read_html("test2.html") |>
html_elements(css = "script[type='application/json']") |>
html_text()
get_table <- function(json) {
# Read the JSON
json_data <- jsonlite::fromJSON(json)
# Extract data and reshape it
table <-
json_data$x[["data"]] |>
as_tibble() |>
t() |>
as_tibble()
# Extract variable names from html
variable_names <-
minimal_html(json_data$x[["container"]]) |>
html_table() %>%
.[[1]] |>
colnames()
# Add column names
colnames(table) <- variable_names
table
}
tables <- lapply(html_data, get_table)
tables
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490629.html
