【发布时间】:2020-09-12 20:37:17
【问题描述】:
总结:使用 trycatch 和 R 的 read_html 函数处理错误和坏页。
我们正在使用 Rs read_html 功能连接到一些 NCAA 体育网站,并且需要识别页面何时出现故障。以下是一些错误页面的示例 URL:
- www.newburynighthawks.com (does not exist)
- http://www.clarkepride.com/sports/womens-basketball/roster/2020-21 (404 not found)
- https://lyon.edu/sports/lyon_sports.html/sports/mens-basketball/roster/2018-19 (not found)
- www.lambuth.edu/athletics/index.html (does not exist)
- https://uvi.edu/pub-relations/athletics/athletics.htm/sports/womens-basketball/roster/2018-19 (page not found)
在使用read_html 时,每个网址都有自己的问题/问题。为了处理这些问题,我编写了一个函数,使用trycatch 在以下情况下检查这些页面的有效性:
check_url_validity <- function(this_url) {
good_url = FALSE
# go to url to check for a rosters page
bad_page_titles = c('Page Not Found', 'Page not found', '404')
result = tryCatch({
team_page <- this_url %>% GET(., timeout(2)) %>% read_html
team_page_title <- team_page %>% html_nodes('title') %>% html_text
team_page_body <- team_page %>% html_nodes('body') %>% html_text
good_page <- !grepl('Page not found', team_page_title) &&
!grepl('Page Not Found', team_page_title) &&
!grepl('404', team_page_title) &&
team_page_title != "" &&
!grepl('Error 404', team_page_body)
if(good_page) { good_url = TRUE }
}, error = function(e) { NA })
return(good_url)
}
在上面链接的 url 上测试这个函数提供了以下内容:
these_urls = c(
'www.newburynighthawks.com',
'http://www.clarkepride.com/sports/womens-basketball/roster/2020-21',
'https://lyon.edu/sports/lyon_sports.html/sports/mens-basketball/roster/2018-19',
'www.lambuth.edu/athletics/index.html',
'https://uvi.edu/pub-relations/athletics/athletics.htm/sports/womens-basketball/roster/2018-19'
)
for (this_url in these_urls) {
print(check_rosters_url(this_url))
}
其中一些页面 (http://www.newburynighthawks.com/) 在 trycatch 中很容易被识别为不良页面,因为没有页面。其他人 (http://www.clarkepride.com/sports/womens-basketball/roster/2020-21) 依靠正文中的字符串匹配来发现页面不好。整体问题是这是一个 hacky 解决方案,我们在这里处理大约 1000 个不同的 URL,并且我们继续在代码行中添加条件来确定 good_page 是 TRUE 还是 FALSE。目前我们最多有5个条件,其中大部分使用grepl来匹配标题和正文中的404和Not Found等短语。
有没有比body中404和Not Found的字符串匹配更好的办法,才能知道这些页面不是好页面?
【问题讨论】:
标签: r error-handling try-catch rvest