r - 无法选择正确的 css 元素以使用 rvest 进行抓取
问题描述
目标:我正在尝试从basketball-reference.com 上抓取NBA 球队的输赢记录。
更广泛地说,我试图更好地理解如何正确使用 CSS 选择器小工具从网站上抓取指定的元素,但希望能找到解决此问题的方法。
我正在使用的网址(https://www.basketball-reference.com/leagues/NBA_2018_standings.html)上有多个表格,所以我尝试使用 CSS 选择器小工具来指定我想要的元素,它是“扩展排名”表 - 大约在页面下方的 1/3。
我已经阅读了各种关于 web 抓取的教程,这些教程涉及rvest
和dplyr
包,以及 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”,这是休斯顿火箭队行的“总体”列中的值),但这似乎突出了一些,但不是所有表格,以及网页上其他表格的随机部分。
任何人都可以提供解决方案吗?如果你能帮助我理解我在哪里/为什么我在做什么是不正确的,那么奖励积分。
提前致谢!
解决方案
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)
推荐阅读
- java - java怎么知道我们指的是哪个类
- azure-functions - 如何使用 Azure CLI PowerShell 从 Azure Functions 读取 appsettings.json
- .net - PowerShell URI 模板解析
- r - 如何使用 Sapply for Pearson 系数迭代列
- python - 获取 RecursionError:比较超过最大递归深度
- powershell - 从 powershell 检查交换邮箱
- xamarin - Xamarin 属性“内容”设置不止一次
- amazon-web-services - 将 AWS Lambda 函数代码直接存储在 S3 存储桶中
- android - RecyclerView 重复 ViewHolders 单选按钮
- c++ - 用空尖括号专门化模板函数:没有它有区别吗?