【问题标题】:How do I use cookies with RCurl?如何在 RCurl 中使用 cookie?
【发布时间】:2010-03-05 18:18:35
【问题描述】:

我正在尝试编写一个通过 REST API 访问某些数据的 R 包。但是,该 API 不使用 http 身份验证,而是依靠 cookie 来保存会话的凭据。

基本上,我想用两个 R 函数替换 bash 脚本中的以下两行:一个用于执行登录,并存储会话 cookie,第二个用于获取数据。

curl -X POST -c cookies.txt -d"username=xxx&password=yyy" http://api.my.url/login
curl         -b cookies.txt                               http://api.my.url/data

我显然不明白 RCurl 如何与 curl 选项一起使用。我的脚本目前有:

library(RCurl)
curl <- getCurlHandle()
curlSetOpt(cookiejar='cookies.txt', curl=curl)
postForm("http://api.my.url/login", username='xxx', password='yyy', curl=curl)
getURL('http://api.my.url/data", curl=curl)

最终的getURL() 失败并显示“未登录”。来自服务器的消息,在postForm() 之后没有cookies.txt 文件存在。

【问题讨论】:

    标签: r curl rcurl


    【解决方案1】:

    一般情况下,您不需要创建 cookie 文件,除非您想研究 cookie。

    鉴于此,实际上,Web 服务器使用代理数据、重定向和隐藏帖子数据,但这应该会有所帮助:

    library(RCurl)
    
    #Set your browsing links 
    loginurl = "http://api.my.url/login"
    dataurl  = "http://api.my.url/data"
    
    #Set user account data and agent
    pars=list(
         username="xxx"
         password="yyy"
    )
    agent="Mozilla/5.0" #or whatever 
    
    #Set RCurl pars
    curl = getCurlHandle()
    curlSetOpt(cookiejar="cookies.txt",  useragent = agent, followlocation = TRUE, curl=curl)
    #Also if you do not need to read the cookies. 
    #curlSetOpt(  cookiejar="", useragent = agent, followlocation = TRUE, curl=curl)
    
    #Post login form
    html=postForm(loginurl, .params = pars, curl=curl)
    
    #Go wherever you want
    html=getURL(dataurl, curl=curl)
    
    #Start parsing your page
    matchref=gregexpr("... my regexp ...", html)
    
    #... .... ...
    
    #Clean up. This will also print the cookie file
    rm(curl)
    gc()
    

    重要

    除了用户名和密码之外,通常还有隐藏的帖子数据。要捕获它,您可能想要,例如在 Chrome 中,使用 Developer tools (Ctrl Shift I) -> Network Tab,以显示帖子字段名称和值.

    【讨论】:

    • 你是个天才! +n 这个很棒的解决方案
    【解决方案2】:

    我的错。 Neal Richter 向我指出 http://www.omegahat.org/RCurl/RCurlJSS.pdf - 这更好地解释了 cookiefilecookiejar 之间的区别。问题中的示例脚本实际上确实 工作。但它仅在不再使用文件时将文件写入磁盘。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      相关资源
      最近更新 更多