通过抓取读取多个表

时间:2015-04-29 17:36:38

标签: xml r web-scraping

我想从http://www.nhl.com/stats/player?navid=nav-sts-indiv#读取R中的一些表格,而单个表格只显示30行,总共> 300。使用XML和readHTMLTables,如何将所有表提取并组合成一个我可以进行分析的大型数据框。

我使用了一个循环来阅读第1-11页,但我感兴趣的表有许多不同的表,并且认为查看每个表以查看总表数/行数并不高效。

    require(XML)
    url='http://www.nhl.com/stats/player?fetchKey=20153ALLSASAll&viewName=summary&sort=points&gp=1&pg='
a=NULL
for(i in 1:11){
    w=paste(url,i,sep='')
    b=readHTMLTable(w)[[3]]
    a=rbind(a,b)
}

请注意,我知道有11个网址,因为我是手动查找的。

有没有人可以想到哪里可以自动计算行/表的总数,所以我不会手动查找。也许有一个我没有遇到过的功能?

1 个答案:

答案 0 :(得分:1)

你可以抓取页数,然后把它扔进你的循环中。这是刮刀的快速扩展:

require(XML)
require(stringr)

url <- 'http://www.nhl.com/stats/player?fetchKey=20153ALLSASAll&viewName=summary&sort=points&gp=1&pg='

# Scrape the first page to get the number of pages
w1 <- paste(url, 1, sep = '')

# Parse using the XPath found by inspecting the page
page_divs <- xpathApply(htmlParse(w1), '//*[@id="statsPage"]/div/div/a')

# Extract the last div
last_div  <- page_divs[length(page_divs)]

# Extact the page
last_url  <- xmlGetAttr(last_div[[1]], "href")

# Extract max page
max_page  <- str_extract(str_extract(last_url, "pg=.\\d"), "[[:digit:]]+")

a <- NULL
for(i in 1:max_page) {
  w <- paste(url, i , sep = '')
  b <- readHTMLTable(w)[[3]]
  a <- rbind(a, b)
}