【问题标题】:Accessing html Tables with rvest使用 rvest 访问 html 表
【发布时间】:2017-10-20 03:07:38
【问题描述】:

所以我想抓取一些 NBA 数据。以下是我目前所拥有的,并且功能完善:

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')

但这似乎不起作用,因为我得到的只是一个空列表。如何访问四因素表?

【问题讨论】:

    标签: html css r rvest


    【解决方案1】:

    我绝不是 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])
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 2020-11-15
      • 2018-03-13
      • 2018-04-03
      • 2017-10-11
      • 2020-04-19
      • 1970-01-01
      相关资源
      最近更新 更多