2017-03-10 8 views
0

いくつかの情報を掻き集めるために、www.geocaching.comからHTML Webページをダウンロードしたいと思います。しかし、私がダウンロードしたいウェブページには、ユーザがログインしているかどうかによって2つの表示方法があります。スクラップしたい情報は、ユーザがログインしたときにのみ表示されます。パスワードポータルからhtmlをダウンロード

以前はdownload.file()

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

をしかし、これはページ内の非ログインダウンロード:URLのリスト(geocache_link_list)からHTMLファイルをダウンロードし、このように別のリスト(geocache_name_list)を使用して、それらに名前を付けるmapply()

私も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内でRSeleniumRCurlのようなものを使ってログインの詳細を入力し、目的のページにリダイレクトしてダウンロードしますか?

答えて

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でデータにアクセスすることができます。

関連する問題