html - 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!
解决方案
您可以尝试使用 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/
然后我不得不从这里使用以下代码:
# 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
推荐阅读
- c# - 如何创建自己的自定义 jsonhandler 来处理“MaxJsonDeserializerMembers”
- sql - 决定给那些薪水+comm <1500的员工加薪20% 获取员工列表将显示他当前的Salary+comm并修改
- algorithm - 元搜索 - 删除不同分辨率的重复图片 - 改进当前方法
- python - 为什么我在读取字节时会得到一个额外的 b 前缀?
- c++ - 使用 MSVC 在 Windows 上编译错误 Botan 库
- r - 使用 ggplot 组合条形图和折线图
- botframework - 如何在具有最小化功能的网站上添加现有机器人
- pytorch - 如何在 pytorch 网站上理解这一点?
- selenium - Cucumber 依赖问题 - 无法加载插件类
- php - 如何在 Linux Ubuntu /opt/lampp/etc/php.ini 中增加 max_input_vars