首页 > 解决方案 > 跳过错误 open.connection(x, "rb") 中的错误:HTTP 错误 404

问题描述

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


标题:“错误”作者:“FJSG”日期:“27/6/2020”输出:html_document

knitr::opts_chunk$set(echo = TRUE)

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

zora_core <- read_html("https://zora.medium.com/the-zora-music-canon-5a29296c6112")

Los_100 <- data.frame(album = html_nodes(zora_core, "h1:not(#96c9)") %>%
                                     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(" ","_")))

货物 <- 功能(网址){
  
         perfil_raw <- read_html(url)
         data.frame(解释 = html_node(perfil_raw,“h1#firstHeading”)%>%
                                 html_text() %>% str_trim(side = "both"))
         
}
lista <- Los_100$liga[1:16] # 位置 16 的 url 不存在如何避免

datos_personales <- map_df(lista,carga)


标签: rweb-scrapinghttp-status-code-404handleerror

解决方案


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

在您的情况下,最好cargatryCatch. 这会运行您作为第一个参数传递的表达式,如果抛出错误,则会将其捕获并传递给 的第二个参数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 的人。它在几行代码中实现了很多并且完全可读。干得好!


推荐阅读