当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。