【问题标题】:skip error Error in open.connection(x, "rb") : HTTP error 404跳过错误 open.connection(x, "rb") 中的错误:HTTP 错误 404
【发布时间】:2020-10-18 10:11:11
【问题描述】:

你好,我是这个迷人的 r 世界的新手,我无法跳过不存在的 url,我该如何处理?并且不要标记为和错误,感谢您的帮助。


标题:“错误” 作者:《FJSG》 日期:“2020 年 6 月 27 日” 输出:html_document

knitr::opts_chunk$set(echo = TRUE)

库(xml2)
图书馆(rvest)
图书馆(tidyverse)
图书馆(润滑)

zora_core %
                                     html_text() %>%
                                     str_trim(side = "both"),
                      解释 = html_nodes(zora_core, "强 em , p#73e0 强") %>%
                                     html_text() %>%
                                     str_remove_all("^by") %>%
                                     str_extract("[a-zA-Z].+(?=[(])") %>% str_trim(side = "both"),
                      año = html_nodes(zora_core, "strong em , p#73e0 strong") %>%
                                     html_text %>%
                                     str_extract("([[:digit:]]){4}"),
                      liga = paste0("https://en.wikipedia.org/wiki/",html_nodes(zora_core, "strong em , p#73e0 strong") %>%
                                     html_text() %>%
                                     str_remove_all("^by") %>%
                                     str_extract("[a-zA-Z].+(?=[(])") %>% str_trim(side = "both") %>% str_replace_all(" ","_")))

货物 % html_text() %>% str_trim(side = "both")) } lista

【问题讨论】:

    标签: r web-scraping http-status-code-404 handleerror


    【解决方案1】:

    了解 R 中的错​​误处理很有用,但在处理 http 请求时,它变得必不可少。

    在您的情况下,最好将carga 包装在tryCatch 中。这会运行您作为第一个参数传递的表达式,如果抛出错误,则会将其捕获并传递给tryCatch 的第二个参数,这是一个函数。

    如果抛出错误,我们需要返回一个包含名为interprete 的单列的数据框,以便map_df 可以将其与其他结果绑定在一起:

    carga_catch <- function(x)
    {
      tryCatch(return(carga(x)),
               error = function(e) return(data.frame(interprete = "**inexistente**")))
    }
    
    map_df(lista, carga_catch)
    #>               interprete
    #> 1        Ella Fitzgerald
    #> 2          Sarah Vaughan
    #> 3         Billie Holiday
    #> 4  Sister Rosetta Tharpe
    #> 5             Lena Horne
    #> 6        Mahalia Jackson
    #> 7          Abbey Lincoln
    #> 8             Etta James
    #> 9         Leontyne Price
    #> 10       Marian Anderson
    #> 11      Dinah Washington
    #> 12                Odetta
    #> 13        Dionne Warwick
    #> 14          The Supremes
    #> 15           Nina Simone
    #> 16       **inexistente**
    
    

    除了错误处理之外,我认为您的代码非常适合刚开始使用 R 的人。它在几行代码中实现了很多,并且完全可读。干得好!

    【讨论】:

    • 非常感谢,看起来很简单,但我真的不知道怎么做,你的cmets帮助我谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 2021-10-31
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多