當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


R rvest html_table 將 html 表解析為 DataFrame

該算法模仿瀏覽器的操作,但會在覆蓋的每個單元格中重複合並單元格的值。

用法

html_table(
  x,
  header = NA,
  trim = TRUE,
  fill = deprecated(),
  dec = ".",
  na.strings = "NA",
  convert = TRUE
)

參數

x

文檔(來自 read_html() )、節點集(來自 html_elements() )、節點(來自 html_element() )或會話(來自 session() )。

header

使用第一行作為標題?如果 NA ,如果第一行包含 <th> 標簽,則將使用第一行。

如果 TRUE ,列名稱與源文檔中的名稱完全相同,這可能需要 post-processing 生成有效的數據幀。

trim

刪除每個單元格內的前導和尾隨空格?

fill

已棄用 - 表中缺失的單元格現在始終自動填充 NA

dec

用作小數位標記的字符。

na.strings

如果 convertTRUE ,則將轉換為 NA 的值的字符向量。

convert

如果 TRUE ,將運行 type.convert() 將文本解釋為整數、雙精度或 NA

當應用於單個元素時,html_table() 返回單個 tibble。當應用於多個元素或文檔時,html_table() 返回 tibbles 列表。

例子

sample1 <- minimal_html("<table>
  <tr><th>Col A</th><th>Col B</th></tr>
  <tr><td>1</td><td>x</td></tr>
  <tr><td>4</td><td>y</td></tr>
  <tr><td>10</td><td>z</td></tr>
</table>")
sample1 %>%
  html_element("table") %>%
  html_table()
#> # A tibble: 3 × 2
#>   `Col A` `Col B`
#>     <int> <chr>  
#> 1       1 x      
#> 2       4 y      
#> 3      10 z      

# Values in merged cells will be duplicated
sample2 <- minimal_html("<table>
  <tr><th>A</th><th>B</th><th>C</th></tr>
  <tr><td>1</td><td>2</td><td>3</td></tr>
  <tr><td colspan='2'>4</td><td>5</td></tr>
  <tr><td>6</td><td colspan='2'>7</td></tr>
</table>")
sample2 %>%
  html_element("table") %>%
  html_table()
#> # A tibble: 3 × 3
#>       A     B     C
#>   <int> <int> <int>
#> 1     1     2     3
#> 2     4     4     5
#> 3     6     7     7

# If a row is missing cells, they'll be filled with NAs
sample3 <- minimal_html("<table>
  <tr><th>A</th><th>B</th><th>C</th></tr>
  <tr><td colspan='2'>1</td><td>2</td></tr>
  <tr><td colspan='2'>3</td></tr>
  <tr><td>4</td></tr>
</table>")
sample3 %>%
  html_element("table") %>%
  html_table()
#> # A tibble: 3 × 3
#>       A     B     C
#>   <int> <int> <int>
#> 1     1     1     2
#> 2     3     3    NA
#> 3     4    NA    NA
源代碼:R/table.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Parse an html table into a data frame。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。