R - 使用rvest包进行网络爬虫

3

我尝试从此网页上的“团队统计”表格中获取数据:

https://www.hockey-reference.com/teams/CGY/2010.html

我没有很多网络爬虫的经验,但已经尝试了XML包和rvest包:

library(rvest)

url <- html("https://www.hockey-reference.com/teams/CGY/2010.html")

url %>%
        html_node(xpath = "//*[@id='team_stats']") 

并且最终得到一个看起来像单个节点的结果:
{xml_node}
<table class="sortable stats_table" id="team_stats" data-cols-to-freeze="1">
[1] <caption>Team Statistics Table</caption>
[2] <colgroup>\n<col>\n<col>\n<col>\n<col>\n<col>\n<col>\n<col>\ ...
[3] <thead><tr>\n<th aria-label="Team" data-stat="team_name" sco ...
[4] <tbody>\n<tr>\n<th scope="row" class="left " data-stat="team ...

我该如何解析它,以仅获取标题和两行表格中的信息?
1个回答

2
你只需要在链的末尾添加html_table:
library(rvest)

url <- read_html("https://www.hockey-reference.com/teams/CGY/2010.html")

url %>%
  html_node(xpath = "//*[@id='team_stats']") %>% 
  html_table()

或者:

library(rvest)

url %>%  
  html_table() %>% 
  .[[1]]

这两种解决方案都会返回:

            Team AvAge GP  W  L OL PTS  PTS%  GF  GA   SRS  SOS TG/G PP PPO   PP% PPA PPOA   PK% SH SHA    S  S%   SA   SV%   PDO
1 Calgary Flames  28.8 82 40 32 10  90 0.549 201 203 -0.03 0.04 5.05 43 268 16.04  54  305 82.30  7   1 2350 8.6 2367 0.916 100.1
2 League Average  27.9 82 41 31 10  92 0.561 233 233  0.00 0.00 5.68 56 304 18.23  56  304 81.77  6   6 2486 9.1 2479 0.911    NA

谢谢!注意:第一种解决方案首先返回一个数据框,而备选解决方案仅返回表格的第一列,因为使用了点占位符和索引。虽然我不抱怨。 - Conner M.
嗯,备用解决方案(.[1])对我来说返回的是表格列表中的第一个元素,而不仅仅是第一列。无论如何,我已经更新了我的答案,使用.[[1]],因为在这一点上我们不需要一个列表,我们只对第一个表格感兴趣,如果我们要从列表中选择多个元素,我们才会使用.[ - tyluRp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接