Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中的readHTMLTable-跳过空值_Html_R_Web Scraping_Null - Fatal编程技术网

R中的readHTMLTable-跳过空值

R中的readHTMLTable-跳过空值,html,r,web-scraping,null,Html,R,Web Scraping,Null,我试图使用R函数readHTMLTable从www.racingpost.com上的在线数据库收集数据。我有一个带有30000个唯一ID的CSV文件,可用于识别单个马。不幸的是,这些ID中的一小部分导致readHTMLTable返回错误: (函数(类、fdef、mtable)中出错: 找不到签名“NULL”的函数“readHTMLTable”的继承方法 我的问题是-是否可以设置一个包装函数,跳过返回空值的ID,然后继续读取剩余的HTML表?读取会在每个空值处停止 到目前为止,我尝试的是: ids

我试图使用R函数readHTMLTable从www.racingpost.com上的在线数据库收集数据。我有一个带有30000个唯一ID的CSV文件,可用于识别单个马。不幸的是,这些ID中的一小部分导致readHTMLTable返回错误:

(函数(类、fdef、mtable)
中出错: 找不到签名“NULL”的函数“readHTMLTable”的继承方法

我的问题是-是否可以设置一个包装函数,跳过返回空值的ID,然后继续读取剩余的HTML表?读取会在每个空值处停止

到目前为止,我尝试的是:

ids = c(896119, 766254, 790946, 556341,  62736, 660506, 486791, 580134, 0011, 580134)
这些都是有效的马ID,但0011将返回空值。然后:

scrapescrape <- function(x) {      
  link <- paste0("http://www.racingpost.com/horses/horse_home.sd?horse_id=",x)      
  if (!is.null(readHTMLTable(link, which=2))) {
     Frame1 <- readHTMLTable(link, which=2)
  }
}

total_data = c(0)
for (id in ids) {
  total_data = rbind(total_data, scrapescrape(id))
}

scrape在阅读HTML表之前,您可以先分析HTML(检查您得到的页面,并找到识别错误结果的方法)

但您也可以确保函数在抛出错误时不返回任何内容(NA),如下所示:

library(XML)

scrapescrape <- function(x) {

  link <- paste0("http://www.racingpost.com/horses/horse_home.sd?horse_id=",x)

    tryCatch(readHTMLTable(link, which=2), error=function(e){NA})

  }
}

ids <- c(896119, 766254, 790946, 556341,  62736, 660506, 486791, 580134, 0011, 580134)

lst <- lapply(ids, scrapescrape)

str(lst)
库(XML)

使用
rvest
刮取,您可以执行以下操作:

require(rvest)
require(purrr)
paste0("http://www.racingpost.com/horses/horse_home.sd?horse_id=", ids) %>% 
  map(possibly(~html_session(.) %>% 
                 read_html %>% 
                 html_table(fill = TRUE) %>% 
                 .[[2]], 
               NULL)) %>% 
  discard(is.null)
最后一行将丢弃所有“失败”的尝试。如果要保留这些尝试,请删除最后一行