【发布时间】:2021-09-16 04:11:34
【问题描述】:
我写了一个嵌套的 for 循环,想把它转换成一个函数。这是我目前拥有的代码:
## Sleeper function
testit <- function(x)
{
p1 <- proc.time()
Sys.sleep(x)
proc.time() - p1 # The cpu usage should be negligible
}
## Set up null objects to fill in loop
episodes = NULL
l = NULL
## Scrape pages and append together
for (season in c(27:38)){
for (episode in c(1:13)){
tryCatch({
if (season == 34 & episode == 3){
l = 'l'
}
new_episode <- read_html(paste0('http://www.chakoteya.net/DoctorWho/', season, '-', episode, '.htm', l)) %>%
html_nodes("p") %>%
html_text() %>%
tibble(value = .)
episodes <- episodes %>% bind_rows(new_episode)
cat(paste('\rseason = ', season, '; episode = ', episode))
testit(2)
}, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
}
如您所见,它在第 27-38 季和第 1-13 季中循环播放。有时这一季只有 12 集,因此tryCatch()。而且,由于我不明白的原因,有时 URL 需要一个 .html 后缀(如果季节 >= 34 和情节 >= 3),有时它需要一个 .htm 后缀,因此是 if (season == 34 & episode == 3) 声明。
我想将其转换为函数,可能使用apply() 或map(),但我的函数技能仍然很初级,我正在苦苦挣扎。
作为最终输出,最好像这样调用一个名为 doctor_who() 的函数:
episodes <- doctor_who(season = c(27:38), episode = c(1:13))
【问题讨论】:
标签: r function for-loop web-scraping rvest