尝试使用tryCatch
。我想要的是运行我存储在page1URLs
中的网址列表,如果其中一个网址存在问题(使用readHTMLTable()
)我想要记录哪些网址然后我想要代码继续下一个url而不会崩溃。
我想我根本就没有正确的想法。谁能建议我怎么做呢?
以下是代码的开头:
baddy <- rep(NA,10,000)
badURLs <- function(url) { baddy=c(baddy,url) }
writeURLsToCsvExtrema(38.361042, 35.465144, 141.410522, 139.564819)
writeURLsToCsvExtrema <- function(maxlat, minlat, maxlong, minlong) {
urlsFuku <- page1URLs
allFuku <- data.frame() # need to initialize it with column names
for (url in urlsFuku) {
tryCatch(temp.tables=readHTMLTable(url), finally=badURLs(url))
temp.df <- temp.tables[[3]]
lastrow <- nrow(temp.df)
temp.df <- temp.df[-c(lastrow-1,lastrow),]
}
答案 0 :(得分:2)
一种通用方法是编写一个完全处理一个URL的函数,返回计算值或NULL以指示失败
FUN = function(url) {
tryCatch({
xx <- readHTMLTable(url) ## will sometimes fail, invoking 'error' below
## more calculations
xx ## final value
}, error=function(err) {
## what to do on error? could return conditionMessage(err) or other...
NULL
})
}
然后使用它,例如,使用命名向量
urls <- c("http://cran.r-project.org", "http://stackoverflow.com",
"http://foo.bar")
names(urls) <- urls # add names to urls, so 'result' elements are named
result <- lapply(urls, FUN)
这些家伙失败了(返回NULL)
> names(result)[sapply(result, is.null)]
[1] "http://foo.bar"
这些是进一步处理的结果
final <- Filter(Negate(is.null), result)