2017-05-04 50 views
1

对Rselenium来说很新,使用Chrome进行调试,然后转移到PhantomJS进行生产(仅仅是因为我可以在没有浏览器窗口弹出的情况下在循环中运行脚本)。http认证使用Rselenium/PhantomJS

我想刮一个https网站,有一个漂亮的香草认证弹出窗口。当我使用Chrome时,我可以使用格式https://user:[email protected]。但是,当我使用phantomjs时,这似乎不起作用。使用RSelenium驱动PhantomJS有没有一种很好的方法来获取证书?

如果没有,是否有更好的方法?具有讽刺意味的是,我可以使用rvest/httr登录该网站......问题在于它非常重java,我真的需要RSelenium进行导航并最终获取所需的数据。

一些示例代码,但不幸的是我无法提供密码保护的网站,我引用:

library(RSelenium) 
library(httr) 
library(wdman) 
selCommand<-wdman::selenium(jvmargs = c("-Dwebdriver.chrome.verboseLogging=true"), 
         retcommand = TRUE) 
cat(selCommand) 
#start Selenium server via shell script 

remDr <- remoteDriver(port = 4567L, browserName = "chrome") 
#remDr <- remoteDriver(port = 4567L, browserName = "phantomjs") 
remDr$open() 
remDr$navigate("https://user:[email protected]") #works with chrome, 
                 #does not work with PhantomJS 

任何帮助表示赞赏,并感谢。

回答

0

您可以使用登录时使用的Cookie登录getAllCookies。然后,在PhantomJS浏览器中,拨打addCookie

0

该呼叫应该首先是http而不是https

library(RSelenium) 

rD <- rsDriver(browser = "phantom") 
remDr <- rD$client 

remDr$navigate("http://user:[email protected]/basic-auth/user/passwd") 
> remDr$getPageSource()[[1]] 
[1] "<html><head></head><body><pre style=\"word-wrap: break-word; white-space: pre-wrap;\">{\n \"authenticated\": true, \n \"user\": \"user\"\n}\n</pre></body></html>" 
rm(rD) 
gc() 

另外,如果这不工作,你可以设置自定义标题:

base64pw <- paste("Basic", 
        base64enc::base64encode(charToRaw("user:passwd"))) 
eCaps <- list("phantomjs.page.customHeaders.Authorization" = base64pw) 
rD <- rsDriver(browser = "phantom", extraCapabilities = eCaps) 
remDr <- rD$client 

remDr$navigate("http://httpbin.org/basic-auth/user/passwd") 
> remDr$getPageSource()[[1]] 
[1] "<html><head></head><body><pre style=\"word-wrap: break-word; white-space: pre-wrap;\">{\n \"authenticated\": true, \n \"user\": \"user\"\n}\n</pre></body></html>" 
rm(rD) 
gc() 
+0

它必须是HTTPS,很遗憾。同时,我甚至无法访问网址......即使我完全忽略用户/传递,并尝试导航到此https网站,然后运行remDr $ getCurrenturl(),我发现它仍然处于:空白,即没有任何改变。 – jsg51483

+0

尝试设置一个自定义标题,显然用实际替换'user:passwd'。如果这不起作用,那么需要特定的网站来进一步研究这个问题。 – jdharrison

+0

不幸的是,没有骰子。只是为了我自己的理解,使用自定义标题的想法是通过调用$ navigate()有效传递的?即,您已经编写了上述代码的自定义标题,将应用于任何基本的http授权弹出窗口?再次感谢你的帮助。 – jsg51483