r - 跳过错误 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)
解决方案
学习 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 的人。它在几行代码中实现了很多并且完全可读。干得好!
推荐阅读
- javascript - 无法在已部署版本中检索图像,而图像在本地主机上运行的反应应用程序中完美加载?
- python - 预期类型字节并得到 str 而不是 udp 客户端错误
- c++ - 了解 C++ 堆栈对象分配
- java - 按集合中的元素查找
- nginx-reverse-proxy - ESXi vCenter 7.0 NginX 反向代理问题
- javascript - 如何从异步函数返回值并将其声明为全局
- android - Vk Api 请求在 android 应用程序中不起作用
- android - 在 android 上使用 opencv 启动 2 个摄像头
- .htaccess - 用于指向自定义域的 DNS CNAME 设置(多租户 SaaS)
- visual-studio - 如何复制我的 Visual Basic 程序(源代码和表单)