r - R webscraping,不确定如何进行
问题描述
对于一个附带项目,我正在尝试收集与梦幻足球相关的 NFL 球员的统计数据。我找到了一个包含我想要的数据的 URL: https ://www.cbssports.com/fantasy/football/stats/QB/2020/ytd/stats/ppr/
我试图在 R 中刮掉它,但没有运气。我已经尝试了很多东西,我得到的最接近的是:
Test1 <- read_html("https://www.cbssports.com/fantasy/football/stats/QB/2020/season/projections/ppr/") %>% html_nodes('.TableBase-bodyTr')
到目前为止,我得到了代码,结果如下:
Test1
{xml_nodeset (69)}
[1] <tr class="TableBase-bodyTr">\n<td class="TableBase-bodyTd \n \n \n \n ">\n <span class="CellPlayerName--sho ...
[2] <tr class="TableBase-bodyTr">\n<td class="TableBase-bodyTd \n \n \n \n ">\n <span class="CellPlayerName--sho ...
[3] <tr class="TableBase-bodyTr">\n<td class="TableBase-bodyTd \n \n \n \n ">\n <span class="CellPlayerName--sho ...
[4] <tr class="TableBase-bodyTr">\n<td class="TableBase-bodyTd \n \n \n \n ">\n <span class="CellPlayerName--sho ...
我尝试将其输入 html_text() 并得到以下结果:
[65] "\n \n \n \n \n \n J. Eason\n \n \n \n QB\n \n \n \n IND\n \n \n \n \n \n \n \n
这只是纯粹的混乱,其中嵌入了相关信息。我还尝试在其上使用 html_table() ,但出现错误。
现在,如果我在“Test1”上使用 View 功能,我可以钻取多层数据并找到我正在寻找的内容,但我想要弄清楚的是如何直接获取该数据。
我真的不知道从这里去哪里。如果有人能给我一些指点,我将不胜感激。我对 HTML 的熟悉程度非常低,我正在尝试阅读更多关于它的内容并理解,但是通过检查页面我能够收集到的是数据存储在“TableBase-bodyTr”类中,这就是为什么我指向那里的节点。
解决方案
表格格式有些奇怪,导致html_table()
. 不太确定如何纠正。
这是抓取行内容然后创建数据框的替代方法。
library(rvest)
page <- read_html("https://www.cbssports.com/fantasy/football/stats/QB/2020/season/projections/ppr/")
#find the rows of the table
rows<-page%>% html_nodes('tr')
#the first 2 rows are the header information skipping those
#get the playname (both short and long verision)
playername <- rows[-c(1, 2)] %>% html_nodes('td span span a') %>% html_text() %>% trimws()
playername <- matrix(playername, ncol=2, byrow=TRUE)
#get the team and position
position <- rows[-c(1, 2)] %>% html_nodes('span.CellPlayerName-position') %>% html_text() %>% trimws()
team <- rows[-c(1, 2)] %>% html_nodes('span.CellPlayerName-team') %>% html_text() %>% trimws()
#get the stats from the table
cols <- rows[-c(1, 2)] %>% html_nodes('td') %>% html_text() %>% trimws()
stats <-matrix(cols, ncol=16, byrow=TRUE)
#make the final answer
answer <- data.frame(playername, position, team, stats[, -1])
#still need to rename the columns
statnames<-c("Name_s", "Name_l", "position", "team", 'GP', 'ATT', 'CMP', 'YDS', 'YDS/G', "TD", 'INT', 'RATE', 'ATT', 'YDS', 'AVG', 'TD', 'FL', 'FPTS', "FPPG")
names(answer) <- statnames
这将使您达到 95%,我没有尝试从网页中自动检索列名。手动复制、粘贴和分配列名更容易。
推荐阅读
- if-statement - VHDL中的计数器内的if语句
- intellij-idea - 我如何获得 PsiMethodCallExpression 对象类型?
- android - 未安装 Cordova android 目标
- java - 获取 IPV6 地址时的错误 Java java.net.NetworkInterface
- regex - AlphaNumeric Regex,可以是所有字母或数字,或两者兼而有之
- ios - collectionview 单元格内的按钮操作 - 尝试使用新的未保存子对象保存对象 -
- amazon-elastic-beanstalk - Asp.net 核心 + Aws Elastic Beanstalk + Bitbucket 管道
- angular - 如何在事件监听器中访问类成员的值?
- c# - udpclient.receive() 突然停止接收
- git - Maven 在部署时从 Nexus 返回工件哈希