R httr后验证下载在交互模式下工作但功能失败

Ant*_*ico 7 cookies https r web-scraping httr

下面的代码在交互模式下工作正常但在函数中使用时失败.它只是两个身份验证POST命令,然后是数据下载.我的目标是让它在一个函数内部工作,而不仅仅是在交互模式下.

这个问题是有点续集的这个问题 .. ICPSR最近更新了他们的网站.以下最小可重复的示例需要一个免费帐户,可在

https://www.icpsr.umich.edu/rpxlogin?path=ICPSR&request_uri=https%3a%2f%2fwww.icpsr.umich.edu%2ficpsrweb%2findex.jsp

我尝试添加Sys.sleep(1)和各种httr::GET/ httr::POST电话但没有任何效果.

my_download <-
    function( your_email , your_password ){

        values <-
            list(
                agree = "yes",
                path = "ICPSR" ,
                study = "21600" ,
                ds = "" ,
                bundle = "rdata",
                dups = "yes",
                email=your_email,
                password=your_password
            )


        httr::POST("https://www.icpsr.umich.edu/cgi-bin/terms", body = values)
        httr::POST("https://www.icpsr.umich.edu/rpxlogin", body = values)

        tf <- tempfile()
        httr::GET( 
            "https://www.icpsr.umich.edu/cgi-bin/bob/zipcart2" , 
            query = values , 
            httr::write_disk( tf , overwrite = TRUE ) , 
            httr::progress()
        )

    }

# fails 
my_download( "email@address.com" , "some_password" )

# stepping through works
debug( my_download )
my_download( "email@address.com" , "some_password" )
Run Code Online (Sandbox Code Playgroud)

编辑失败只需下载此页面就好像没有登录(而不是数据集),因此由于某种原因丢失了身份验证.如果您已登录到icpsr,请使用隐私浏览查看页面 -

https://www.icpsr.umich.edu/cgi-bin/bob/zipcart2?study=21600&ds=1&bundle=rdata&path=ICPSR

谢谢!

Ist*_*sta 1

发生这种情况是因为httr包将状态(例如 cookie)存储在handle每个 URL 中(请参阅 参考资料?handle)。

在这种特殊情况下,尚不清楚到底是什么让它起作用,但一种策略是在验证和请求数据之前包含一个GET请求。https://www.icpsr.umich.edu/cgi-bin/bob/例如,

my_download <-
    function( your_email , your_password ){
        ## for some reason this is required ...
        httr::GET("https://www.icpsr.umich.edu/cgi-bin/bob/")
        values <-
            list(
                agree = "yes",
                path = "ICPSR" ,
                study = "21600" ,
                ds = "" ,
                bundle = "rdata",
                dups = "yes",
                email=your_email,
                password=your_password
            )
        httr::POST("https://www.icpsr.umich.edu/rpxlogin", body = values)
        httr::POST("https://www.icpsr.umich.edu/cgi-bin/terms", body = values)
        tf <- tempfile()
        httr::GET( 
            "https://www.icpsr.umich.edu/cgi-bin/bob/zipcart2" , 
            query = values , 
            httr::write_disk( tf , overwrite = TRUE ) , 
            httr::progress()
        )
    }
Run Code Online (Sandbox Code Playgroud)

似乎工作正常,但目前尚不清楚GEThttps://www.icpsr.umich.edu/cgi -bin/bob/` 的请求到底做了什么或为什么需要它。