2017-08-07 40 views
1

我試圖使用POST函數訪問R中的以下URL httr庫。我需要提取一些開發腳本所用的貨幣匯率。我在驗證工具內有不同時間段時遇到問題。使用POST&HTTR以CSFR令牌登錄R

https://www.oanda.com/fx-for-business/historical-rates/auth/login/ 

我用下面的代碼

library(httr) 

     Cookie = paste('opc_id=599C877C-7B4C-11E7-A634-FD6593E2D6B9;', 'csrftoken=EJqIgiufV77Nlv4E54mKoFcxhKGJgnO4cdQzUy2ehaayjD5FX21F8MznpHm0o4W5;','sessionid "6bc5s0qnswsue0pxe3st83ezf6m9cdl5;') 

    headers = list (
    Host= "www.oanda.com", 
     "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0", 
     Accept = "*/*", 
     "Accept-Language" = "en-US,en;q=0.5", 
     "Accept-Encoding" = "gzip, deflate, br", 
     "Content-Type"= "application/x-www-form-urlencoded; charset=UTF-8", 
     Referer = "https://www.oand 

a.com/fx-for-business/historical-rates", 
    "Content-Length" = 64, 
    "X-Requested-With" = "XMLHttpRequest", 
    Cookie = Cookie, Connection= "keep-alive") 

    .headers = character(headers) 

    par = list (
    email = "user", 
    password = "pass", 
    redirect="" 
    ) 

    POST("https://www.oanda.com/fx-for-business/historical-rates/auth/login/",body = pars, add_headers(.headers)) 

最後一行的結果如下。該腳本需要一個CSFR令牌,我該如何生成它?

 <h1>Forbidden 
      <span>(403)</span> 
     </h1> 
     <p>CSRF verification failed. Request aborted.</p> 
     <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> 
     <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for &#39;same-origin&#39; requests.</p> 

的GET & POST的結構有以下

GET https://www.oanda.com/static/sfb/hcc/templates/html/en/popup.login.html?_=1502097958941 
    POST https://www.oanda.com/fx-for-business/historical-rates/auth/login/ 
    GET https://www.oanda.com/fx-for-business/historical-rates/getUser/?_=1502097958942 
    GET https://www.oanda.com/fx-for-business/historical-rates/message/messages/?_=1502097958943 
    GET https://www.oanda.com/static/sfb/hcc/templates/html/en/banner.expiry.html?_=1502097958944 
    GET https://www.oanda.com/static/sfb/hcc/templates/html/en/popup.login.success.html?_=1502097958945 

回答

1

溶液駐留在模擬的Web瀏覽器內部R. 的代碼用於實現該被以下

library(wdman) #I don't know if this library is necessary 
    library(RSelenium) 

    selServ <- selenium(jvmargs = c("-Dwebdriver.chrome.verboseLogging=true")) 
    remDr <- remoteDriver(port = 4567L, browserName = "chrome") 
    remDr$open() 

    ##From here you need to access with your login details inside the browser 

    remDr$navigate(url) 


    df=remDr$getPageSource() 
+0

您也可以在無頭模式下使用chrome(目前是unix和OSX),請參閱此處的第二種方法https://github.com/ropensci/RSelenium/issues/138 – jdharrison