我正在尝试编写一个通过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
Run Code Online (Sandbox Code Playgroud)
我显然不明白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)
Run Code Online (Sandbox Code Playgroud)
最终getURL()
失败并显示"未登录".来自服务器的消息,并且在postForm()
没有cookies.txt
文件之后.
ant*_*nio 17
通常,您不需要创建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()
Run Code Online (Sandbox Code Playgroud)
除了用户名和密码之外,通常还会有隐藏的帖子数据.要捕获它,您可能需要(例如在Chrome中)使用Developer tools
(Ctrl Shift I) - > Network Tab
,以显示帖子字段名称和值.
我的错.尼尔里希特向我指出http://www.omegahat.org/RCurl/RCurlJSS.pdf - 这更好地解释了cookiefile
和之间的区别cookiejar
.在问题中的示例脚本实际上没有工作.但它只在不再使用时将文件写入磁盘.
归档时间: |
|
查看次数: |
7675 次 |
最近记录: |