【问题标题】:Receiving "missing value where TRUE / FALSE needed" error message when web scraping网页抓取时收到“需要 TRUE / FALSE 的缺失值”错误消息
【发布时间】:2020-12-18 20:09:48
【问题描述】:

我正在编写代码以从博客中抓取数据。由于帖子是由两个不同的作者创建的,而我只想从一个作者那里获取数据,所以我创建了一个带有 if 的函数来尝试解决这个问题。但是当我在博客地址上运行该函数时,我收到以下错误消息:“错误:缺少 TRUE / FALSE 需要的值”。有谁知道这意味着什么,我能做些什么来解决它?

功能代码:

extract_articles_blogger_preto <- function(x){
  tryCatch({
    webpage <- read_html(x) 
    text <- html_nodes(webpage, ".cabecalho") %>% html_nodes(".corpo")
    i <- 0
    pular_texto <- FALSE
    article <- ""
    for (p in text){
      if (i==0){
        i <- 1
      }
      else if(i==1){
        i <- 2
        }
      else if(i==2){
        autor <- html_nodes(p, "a[href]") %>% html_attr("href")
        i <- 3
        if (str_detect(autor[2], "rainhafragil")){
          pular_texto <- FALSE
        } else {
          pular_texto <- TRUE
        }
      }
        else if(i==3){
        if (pular_texto==FALSE){
          article <- str_c(article, html_text(text), "\n")
        }
        i <-0
      }
    }
    return(article) 
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

#Trying to apply the function to the blog address:

extract_articles_blogger_preto("http://web.archive.org/web/20070430023653mp_/http://fragilreino.blogger.com.br/2002_12_01_archive.html")

#Error message:"missing value where TRUE / FALSE needed"

【问题讨论】:

    标签: r if-statement web-scraping


    【解决方案1】:

    需要 TRUE/FALSE 的缺失值意味着您有一个 if() 语句想要检查某事物是 TRUE 还是 FALSE,但它看到的是缺失值 NA

    我最好的猜测是问题出在这一行:

    if(str_detect(autor[2], "rainhafragil")){
    

    如果autor 的长度为1,则autor[2] 不存在,str_detect(autor[2], ...) 将给出NA。你可能想改成if(length(autor) &gt; 1 &amp;&amp; str_detect(...)){

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      相关资源
      最近更新 更多