R - 使用rvest刮取受密码保护的网站,而无需在每次循环迭代中登录

时间:2016-01-30 23:57:56

标签: html r web-scraping rvest

我试图使用rvest包从R中受密码保护的网站抓取数据。我的代码当前在循环的每次迭代中登录到网站,该循环将运行大约15,000次。这看起来非常低效,但我还没有找到解决方法,因为每次都没有先登录而跳转到不同的URL会返回到网站的登录页面。我的代码的简化如下:

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部分。

有没有人建议如何在没有登录循环的每次迭代的情况下实现这种抓取?

谢谢!晏

1 个答案:

答案 0 :(得分:0)

你可以将会话保存在一个变量中,但我猜你不会节省那么多时间。 这是我的网页抓取脚本:

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)
          }
         }