首页 > 解决方案 > 大学篮球统计数据的网络抓取表

问题描述

我是网络抓取的新手,并且正在从事一个测试项目,我正在尝试为这个特定团队抓取以下网站上的每个数据表。应该有 15 个表,但是当我运行我的代码时,它似乎只提取了 15 个表中的前 6 个。我该如何获取其余的表?

这是代码:

library(tidyverse)
library(rvest)
library(stringr)
library(lubridate)
library(magrittr)
iowa_stats<- read_html("https://www.sports-reference.com/cbb/schools/iowa/2021.html")

iowa_stats %>% html_table()

编辑:所以我决定更深入地研究这个问题,看看我是否能得到更多的见解。所以我决定从调用 html_table 命令时没有出现的第一个表开始,它是“Totals”表。我做了以下操作,沿着 html 的路径一直到表格,看看我是否能找出问题所在。为此,我使用了以下代码。

iowa_stats %>% html_nodes("body") %>% html_nodes("div#wrap") %>% html_nodes("div#all_totals.table_wrapper")

这是我在收到错误之前所能得到的。在下一步中,应该有以下内容: div#div_totals.table_container.is_setup 存储表的位置,但如果我将其添加到上述代码中,则它不存在。当我键入以下内容时,它也不存在。

iowa_stats %>% html_nodes("body") %>% html_nodes("div#wrap") %>% html_nodes("div#all_totals.table_wrapper") %>% html_nodes("div")

对html / css更好的人是否知道为什么会这样?

标签: rweb-scrapingrvest

解决方案


看起来这个网页正在将一些表格存储为评论。为了解决这个问题,读取并保存网页。删除评论标签,然后正常处理。

library(rvest)
library(dplyr)

iowa_stats<- read_html("https://www.sports-reference.com/cbb/schools/iowa/2021.html")
#Only save and work with the body
body<-html_node(iowa_stats,"body")
write_xml(body, "temp.xml")

#Find and remove comments
lines<-readLines("temp.xml")
lines<-lines[-grep("<!--", lines)]
lines<-lines[-grep("-->", lines)]
writeLines(lines, "temp2.xml")

#Read the file back in and process normally
body<-read_html("temp2.xml")
html_nodes(body, "table") %>% html_table()

推荐阅读