rvest html_table()使用第二行作为标头

发布于 2025-02-03 04:49:17 字数 389 浏览 3 评论 0原文

我正在尝试从FBREF上的表中刮擦数据,但是表包含两个标头,将子标题合并到第一行数据中。有谁知道如何跳过第一行并将第二行用作表标头以维护数据类型?这是我下面的代码。

library(rvest)
library(dplyr)

team_link = "https://fbref.com/en/squads/cff3d9bb/Chelsea-Stats-All-Competitions"
team_page = read_html(team_link)

shooting_table = team_page %>% html_nodes("#all_stats_shooting") %>%
  html_table()

shooting_table = shooting_table[[1]]

I am trying to scrape data from a table on fbref however the tables contain two headers with the subheader being incorporated into the first row of data. Does anyone know how to skip the first line and use the second line as the table header so that data types can be maintained? Here is my code below.

library(rvest)
library(dplyr)

team_link = "https://fbref.com/en/squads/cff3d9bb/Chelsea-Stats-All-Competitions"
team_page = read_html(team_link)

shooting_table = team_page %>% html_nodes("#all_stats_shooting") %>%
  html_table()

shooting_table = shooting_table[[1]]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暖伴 2025-02-10 04:49:17

您可以使用Janitor软件包,

library(janitor)

shooting_table %>%
  row_to_names(1)

该软件包为我们提供:

# A tibble: 28 × 23
   Player     Nation Pos   Age   `90s` Gls   Sh    SoT   `SoT%` `Sh/90` `SoT/90` `G/Sh` `G/SoT` Dist  FK    PK   
   <chr>      <chr>  <chr> <chr> <chr> <chr> <chr> <chr> <chr>  <chr>   <chr>    <chr>  <chr>   <chr> <chr> <chr>
 1 Edouard M… sn SEN GK    29    34.0  0     0     0     ""     0.00    0.00     ""     ""      ""    0     0    
 2 Antonio R… de GER DF    28    33.7  3     48    13    "27.1" 1.42    0.39     "0.06" "0.23"  "19.… 0     0    
 3 Thiago Si… br BRA DF    36    29.4  3     18    5     "27.8" 0.61    0.17     "0.17" "0.60"  "10.… 0     0    
 4 Mason Mou… eng E… MF,FW 22    26.3  11    75    27    "36.0" 2.86    1.03     "0.13" "0.37"  "17.… 6     1    

You can use the janitor package

library(janitor)

shooting_table %>%
  row_to_names(1)

Which gives us:

# A tibble: 28 × 23
   Player     Nation Pos   Age   `90s` Gls   Sh    SoT   `SoT%` `Sh/90` `SoT/90` `G/Sh` `G/SoT` Dist  FK    PK   
   <chr>      <chr>  <chr> <chr> <chr> <chr> <chr> <chr> <chr>  <chr>   <chr>    <chr>  <chr>   <chr> <chr> <chr>
 1 Edouard M… sn SEN GK    29    34.0  0     0     0     ""     0.00    0.00     ""     ""      ""    0     0    
 2 Antonio R… de GER DF    28    33.7  3     48    13    "27.1" 1.42    0.39     "0.06" "0.23"  "19.… 0     0    
 3 Thiago Si… br BRA DF    36    29.4  3     18    5     "27.8" 0.61    0.17     "0.17" "0.60"  "10.… 0     0    
 4 Mason Mou… eng E… MF,FW 22    26.3  11    75    27    "36.0" 2.86    1.03     "0.13" "0.37"  "17.… 6     1    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文