2017-03-10 11 views
0

일부 정보를 긁어 내기 위해 www.geocaching.com에서 HTML 웹 페이지를 다운로드하고 싶습니다. 그러나 내가 다운로드하고자하는 웹 페이지는 사용자가 로그인했는지 여부에 따라 두 가지 방법으로 표시됩니다. 사용자가 로그인 한 경우에만 정보를 찾을 수 있습니다.비밀번호 포털을 통해 html을 다운로드하십시오.

이전에는 download.file()을 사용했습니다. mapply()은 (geocache_link_list) URL 목록에서 HTML 파일을 다운로드하고 다음과 같이 다른 목록 (geocache_name_list)를 사용하여 이름을 지정합니다 :

mapply(function(x,y) download.file(x,y), geocache_link_list, geocache_name_list) 

을하지만,이 페이지에 비 로그인 다운로드합니다.

는 또한 RCurl을 사용하려고하지만,이 또한 페이지에서 비 로그인 다운로드 그래서 나는 mapply 기능에 통합하려고 시도하지 :에서 브라우저를 실행하는 방법이 있나요

library(RCurl) 
baseurl <- geocache_link_list[1] 
un <- readline("Type the username:") 
pw <- readline("Type the password:") 
upw <- paste(un, pw, sep = ":") 

R 내에서 RSelenium 또는 RCurl과 같은 것을 사용하여 로그인 세부 정보를 입력 한 다음 원하는 페이지로 리디렉션하고 다운로드하십시오.

답변

1

쉽습니다.

library(RCurl) 
library(xml2) 

html_inputs <- function(p, xpath = "//form/input") { 
    xml_find_all(p, xpath) %>% {setNames(as.list(xml_attr(., "value")), xml_attr(., "name"))} 
} 
get_header <- function(){ 
    ## RCurl设置, 直接把cookie粘贴过来,即可登录 
    myHttpheader<- c(
    "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71", 
    # "Accept" = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", 
    "Accept-Language" = "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", 
    # "Accept-Encoding"="gzip, deflate", 
    "Connection"="keep-alive", 
    DNT = 1, 
    "Upgrade-Insecure-Requests" = 1, 
    "Host" = "www.geocaching.com") 

    file_cookie <- "cookies.txt" 

    ch <- getCurlHandle(# cainfo="pem/cacert.pem", 
    # ssl.verifyhost=FALSE, ssl.verifypeer = FALSE, 
    followlocation = TRUE, 
    verbose = TRUE, 
    cookiejar = file_cookie, cookiefile = file_cookie, 
    httpheader = myHttpheader)#带上百宝箱开始上路 
    tmp <- curlSetOpt(curl = ch) 
    return(ch) 
} 
ch <- get_header() 
h <- basicHeaderGatherer() 

#input your username and password here 
user <- "kongdd" 
pwd <- "****" 
p <- getURL("https://www.geocaching.com/account/login", curl = ch) 
tooken <- html_inputs(read_html(p))[1] 
params <- list(Password = user, 
       Username = pwd) %>% c(., tooken) 
p2 <- postForm("https://www.geocaching.com/account/login", curl = ch, 
     .params = params) 

grep("kongdd", p2)#If 1 returned, it indicate you have login successfully. 

성공적으로 로그인 한 후에는 매개 변수 curl과 데이터에 액세스 할 수 있습니다.