如何将cookies与RCurl一起使用?
我试图编写一个R包,通过RESTAPI访问一些数据。但是,API不使用http身份验证,而是依赖cookie来保存会话的凭据 本质上,我想用两个R函数替换bash脚本中的以下两行:一个用于执行登录并存储会话cookie,另一个用于获取数据如何将cookies与RCurl一起使用?,r,curl,rcurl,R,Curl,Rcurl,我试图编写一个R包,通过RESTAPI访问一些数据。但是,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
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)
库(RCurl)
卷曲我的不好。尼尔·里克特向我指出——这更好地解释了cookiefile
和cookiejar
之间的区别。问题中的示例脚本确实有效。但它只在不再使用时将文件写入磁盘 通常不需要创建cookie文件,除非您想研究cookie
有鉴于此,实际上,web服务器使用代理数据、重定向和隐藏post数据,但这应该有帮助:
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)->网络选项卡
,以显示帖子字段名称和值 你真是个天才+这是一个非常棒的解决方案