首页 > 解决方案 > 无法选择正确的 css 元素以使用 rvest 进行抓取

问题描述

目标:我正在尝试从basketball-reference.com 上抓取NBA 球队的输赢记录。

更广泛地说,我试图更好地理解如何正确使用 CSS 选择器小工具从网站上抓取指定的元素,但希望能找到解决此问题的方法。

我正在使用的网址(https://www.basketball-reference.com/leagues/NBA_2018_standings.html)上有多个表格,所以我尝试使用 CSS 选择器小工具来指定我想要的元素,它是“扩展排名”表 - 大约在页面下方的 1/3。

我已经阅读了各种关于 web 抓取的教程,这些教程涉及rvestdplyr包,以及 CSS 选择器 web 浏览器插件(我已经安装在 Chrome 中,我选择的浏览器)。这就是我想要的。

到目前为止,这是我的代码:

url <- "https://www.basketball-reference.com/leagues/NBA_2018_standings.html"
css <- "#expanded_standings"

url %>%
  read_html() %>%
  html_nodes(css) %>%
  html_table()

此代码的结果是错误:

Error: html_name(x) == "table" is not TRUE

当我删除最后一行代码时,我得到:

url %>%
  read_html() %>%
  html_nodes(css)

{xml_nodeset (0)}

我定义 CSS 对象的方式/我如何使用 CSS 选择器工具似乎存在问题。我一直在做的是单击所需表格的最右边缘,以便表格周围有一个矩形。

我还尝试单击表格中的特定“单元格”(即“65-17”,这是休斯顿火箭队行的“总体”列中的值),但这似乎突出了一些,但不是所有表格,以及网页上其他表格的随机部分。

任何人都可以提供解决方案吗?如果你能帮助我理解我在哪里/为什么我在做什么是不正确的,那么奖励积分。

提前致谢!

标签: rweb-scrapingcss-selectorsrvest

解决方案


library(rvest)
library(dplR)
library(stringr)
library(magrittr)

url <- "https://www.basketball-reference.com/leagues/NBA_2018_standings.html"
css <- "#expanded_standings"
css <- "#all_expanded_standings"

webpage <- read_html(url)
print(webpage)
mynode <- html_nodes(webpage,css)

mystr <- toString(mynode)
mystr <- gsub("<!--","",mystr)
mystr <- gsub("-->","",mystr)

newdiv <- read_html(mystr)

newtable <- html_nodes(newdiv,"#expanded_standings")
newframe <- html_table(newtable)

print(newframe)

推荐阅读