首页 > 解决方案 > rvest 和 NHL 统计数据的 Css 选择器问题

问题描述

我想从 hockey-reference.com 抓取数据,特别是从这个链接:

https://www.hockey-reference.com/leagues/NHL_1991.html

我想要第四个表,称为“团队统计”,我还想减去第一行和最后一行(但这可以是另一次)。

最初,我想使用 1991 链接进行抓取,但我希望最终抓取 1991 年到 2017 年的每个链接。

library(tidyverse)
library(rvest)

stat_urls <- "https://www.hockey-reference.com/leagues/NHL_1991.html"

现在,为简单起见,我只有 1991 年的链接。在使用实际网页的“检查”源进行了相当彻底的搜索后,即使我尝试了多种不同的 CSS 选择,我似乎也找不到正确的 CSS 选择。我尝试了以下 CSS 选择:

table#stats.sortable.stats_table.now.sortable
#stats
#all_stats
#all_stats > div.table_outer_container
#stats
#stats > tbody
#div_stats (and all sorts of combos with this one)

在以下代码中使用时,这些都不起作用:

team_stats <- stat_urls %>% 
 read_html() %>%
 html_nodes("#stats") %>% 
 html_table(header = T)

所有使用“xpath=”的尝试也都失败了。对此的任何帮助都将是绝对惊人的,Go Preds!


标签: htmlcssrrvest

解决方案


您可以尝试使用 RSelenium。在这里看到了类似的答案:Web Scraping Basketball Reference using R。

library(rvest)
library(RSelenium)
startServer() 
remDr<-remoteDriver(browserName = "chrome")
remDr$open()

remDr$navigate("https://www.hockey-reference.com/leagues/NHL_1991.html")
page <- read_html(remDr$getPageSource()[[1]])
table <- html_table(page, fill = TRUE)
table[[28]]

虽然安装 selenium 很痛苦,我也会尝试帮助解决这个问题,但我前一段时间安装了它,所以不太记得了。祝你好运


来自发布原始问题的人:

上面的答案有效,但我必须通过 Homebrew:

https://brew.sh/

然后我不得不从这里使用以下代码:

在 Mac Chrome 上使用 Selenium

# download selenium jar
curl -L0 https://selenium-release.storage.googleapis.com/3.9/selenium- 
server-standalone-3.9.1.jar -o selenium-server-standalone.jar

# install chromedriver
brew install chromedriver

# start chrome driver
brew services start chromedriver                                                                                                                                                                      
#==> Successfully started `chromedriver` 
(label:homebrew.mxcl.chromedriver)

# start selenium server
java -jar selenium-server-standalone.jar                                                                                                                                                                           
#14:38:20.684 INFO - Selenium build info: version: '3.9.1', revision: 
'63f7b50'
#14:38:20.685 INFO - Launching a standalone Selenium Server on port 
4444

推荐阅读