【问题标题】:in a loop: skip a certain type of error (R)在循环中:跳过某种类型的错误(R)
【发布时间】:2018-12-21 07:21:20
【问题描述】:

我使用的代码来自: https://www.r-bloggers.com/htmltotext-extracting-text-from-html-via-xpath/ cos在github上:

https://github.com/tonybreyal/Blog-Reference-Functions/blob/master/R/htmlToText/htmlToText.R

它创建一个从 html 中提取文本的命令:

htmlToText

我有一个循环如下:

for(i in 1:10000){
input <- URL[i]
txt <- htmlToText(input)
write.table(txt, file = paste0(URL[i], ".txt", sep=""))
}

当出现以下错误时,我希望 ito 转到下一个 i:

Error in function (type, msg, asError = TRUE)  :    "Could not resolve host: NA"

有没有办法做到这一点? 使用此代码可能会帮助许多其他人 谢谢

【问题讨论】:

  • read_html 之前添加if(is.na(input)) next ?
  • 这个问题与您删除的previous question 有何不同?同样,您没有提供足够的详细信息。 read_html 来自哪里?谷歌告诉我rvesttextreadr 都有一个read_html 函数。
  • 当它得到一个不同的错误时怎么办?它应该继续还是应该停止?
  • 我尝试了以下方法,但没有成功:status
  • 这是我每次遇到的唯一错误类型。

标签: r loops error-handling skip


【解决方案1】:

对于以后的帖子,请查看如何提供minimal reproducible example/attempt;这包括明确说明您使用了哪些软件包。

这里我假设您使用的是来自rvestread_html

您可以使用tryCatch 来避免退出循环。我也会用lapply 替换for 循环。

这是一个例子

library(rvest)
URL <- c("http://asd", "http://had.co.nz");
lst <- lapply(URL, function(ss)
    result <- tryCatch(
        read_html(ss),
        error = function(e) {
            print(sprintf("Could not resolve host: %s", ss));
            return(NULL);
        }
    ))
#[1] "Could not resolve host: http://asd"

lst;
#[[1]]
#NULL
#
#[[2]]
#{xml_document}
#<html lang="en">
#[1] <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8 ...
#[2] <body id="page-top" class="index">\n\n<!-- Navigation -->\n<nav class="na ...

【讨论】:

  • 谢谢!我会使用 lapply 的建议!
猜你喜欢
  • 2019-11-23
  • 2014-08-29
  • 2018-01-25
  • 2023-03-08
  • 1970-01-01
  • 2020-09-12
  • 2013-01-22
  • 1970-01-01
  • 2015-08-20
相关资源
最近更新 更多