2017-10-20 63 views
0

所以我想抓取一些NBA数据。以下是我迄今为止,它是完美的功能:使用rvest访问html表格

install.packages('rvest') 
library(rvest) 

url = "https://www.basketball-reference.com/boxscores/201710180BOS.html" 
webpage = read_html(url) 
table = html_nodes(webpage, 'table') 
data = html_table(table) 

away = data[[1]] 
home = data[[3]] 

colnames(away) = away[1,] #set appropriate column names 
colnames(home) = home[1,] 

away = away[away$MP != "MP",] #remove rows that are just column names 
home = home[home$MP != "MP",] 

的问题是,这些表不包括球队的名字,这是很重要的。为了获得这些信息,我想我会在网页上刮掉四个因素表,但是,rvest似乎并不认为这是一张表。包含四个因素表DIV的是:

<div class="overthrow table_container" id="div_four_factors"> 

并且表:

<table class="suppress_all sortable stats_table now_sortable" id="four_factors" data-cols-to-freeze="1"><thead><tr class="over_header thead"> 

这让我觉得,我可以沿着

table = html_nodes(webpage,'#div_four_factors') 
行通过一些访问表

但这似乎不工作,因为我只是得到一个空的列表。我怎样才能访问四个因素表?

回答

0

我绝不是一个HTML专家,但似乎你感兴趣的表已经在源代码中注释掉了,然后在渲染之前的某个时刻评论被覆盖。

如果我们假设主队始终排名第二,我们可以只使用位置参数和刮页面上的其他表:

table = html_nodes(webpage,'#bottom_nav_container') 
teams <- html_text(table[1]) %>% 
    stringr::str_split("Schedule\n") 

away$team <- trimws(teams[[1]][1]) 
home$team <- trimws(teams[[1]][2]) 

显然不是最干净的解决方案,但生活就是这样,在世界网页抓取