簡體   English   中英

用rvest訪問html表

[英]Accessing html Tables with rvest

所以我想抓取一些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專家,但看來您感興趣的表已在源代碼中注釋掉,然后在呈現之前在某個時候覆蓋了注釋。

如果我們假設Home團隊總是排在第二位,那么我們可以使用位置參數並在頁面上抓取另一個表:

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

顯然,這不是最干凈的解決方案,但網頁抓取的世界就是如此

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM