2016-08-04 75 views
1

我开发了一些代码来抓取基于this topic的流量数据。我需要在登录后刮很多页面,但现在我的代码似乎反复登录每个网址的网站。如何“重用”会话以避免重复登录,以便希望代码可以更快运行?这里的伪代码:如何重复使用会话以避免在使用rvest进行重复登录时重复登录?

generateURL <- function(siteID){return siteURL} 

scrapeContent <- function(siteURL, session, filled_form){return content} 

mainPageURL <- 'http://pems.dot.ca.gov/' 
pgsession <- html_session(mainPageURL) 
pgform <- html_form(pgsession)[[1]] 
filled_form <- set_value(pgform, 'username'='myUserName', 'password'='myPW') 

siteIDList = c(1,2,3) 
vectorOfContent <- vector(mode='list', length=3) #to store all the content 

i=1 
for (siteID in siteIDList){ 
    url = generateURL(siteID) 
    content = scrapeContent(url, pgsession, filled_form) 
    vectorOfContent[[i]]=content 
    i = i +1} 

我读了rvest文档,但没有这方面的细节。我的问题:如何'重新使用'会话以避免重复登录?谢谢!

回答

1

你可以做这样的事情:

require(rvest) 
pgsession <- html_session(mainPageURL) 
pgform <- html_form(pgsession)[[1]] 
filled_form <- set_value(pgform, 'username'='myUserName', 'password'='myPW') 
s <- submit_form(pgsession, pgform) # s is your logged in session 

vectorOfContent <- vector(mode='list', length=3) 

for (siteID in siteIDList){ 
    url <- generateURL(siteID) 
    # jump_to navigates within the session, read_html parses the html 
    vectorOfContent[[siteID]]=s %>% jump_to(generateURL) %>% read_html() 
    } 
+0

谢谢! jump_to()实质上就是我正在寻找的。回复晚了非常抱歉。 – user3768495