我正在尝试使用 rvest 包从 R 中受密码保护的网站中抓取数据。我的代码当前在循环的每次迭代中都会登录到网站,该循环将运行大约 15,000 次。这看起来效率很低,但我还没有找到解决方法,因为每次都跳转到不同的网址而不先登录,然后返回到网站的登录页面。我的代码的简化如下:
library(rvest)
url <- password protected website url within quotes
session <-html_session(url)
form <-html_form(session)[[1]]
filled_form <- set_values(form,
`username` = email within quotes,
`password` = password within quotes)
start_table <- submit_form(session, filled_form) %>%
jump_to(url from which to scrape first table within quotes) %>%
html_node("table.inlayTable") %>%
html_table()
data_table <- start_table
for(i in 1:nrow(data_ids))
{
current_table <- try(submit_form(session, filled_form) %>%
jump_to(paste(first part of url within quotes, data_ids[i, ], last part of url within quotes, sep="")) %>%
html_node("table.inlayTable") %>%
html_table())
data_table <- rbind(data_table, current_table)
}
为了简单起见,我处理 try 函数中可能引发的任何错误的方式被抑制。请注意,data_ids 是一个数据框,其中包含要在每次新迭代时更新的 url 部分。
有人建议如何在循环的每次迭代中不登录的情况下实现这种抓取吗?
谢谢!扬
您可以将会话保存在变量中,但我猜您不会节省那么多时间。 这是我的网页抓取脚本:
library(rvest)
url <- "https://"
session <- html_session(url)
form <- html_form(session)[[1]]
filled_form <- set_values(form,`[login]` = "xxx",`[password]` = "xxx")
session <- submit_form(session,filled_form)
for (i in unique(id)) {
link <- paste0("https://",i,"xxx")
df_all <- session %>% jump_to(link) %>% html_table()
if ( length(df_all) != 0 ) {
my_df <- as.data.frame(df_all[n],optional = TRUE)
database <- rbind(my_df,database)
cat("Data saved for",i)
} else {
cat("No data for",i)
}
}