【问题标题】:http authentication using Rselenium/PhantomJS使用 Rselenium/PhantomJS 的 http 身份验证
【发布时间】:2017-10-03 04:58:54
【问题描述】:

Rselenium 的新手,使用 Chrome 进行调试,然后将转移到 PhantomJS 进行生产(只是因为我可以循环运行脚本而不会弹出浏览器窗口)。

我正在尝试抓取一个具有非常普通的身份验证弹出窗口的 https 网站。当我使用 Chrome 时,我可以使用 https://user:pass@www.somewebsite.com 格式。但是,似乎当我使用 phantomjs 时,这不起作用。有没有一种使用 RSelenium 来驱动 PhantomJS 的管道输入凭据的好方法?

如果没有,有更好的方法吗?具有讽刺意味的是,我可以使用 rvest/httr 登录到该站点...问题是它是如此的 java-heavy 以至于我真的需要 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:pass@www.somewebiste.com") #works with chrome, 
                                                        #does not work with PhantomJS

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

【问题讨论】:

    标签: r selenium phantomjs rvest


    【解决方案1】:

    应该首先调用http而不是https

    library(RSelenium)
    
    rD <- rsDriver(browser = "phantom")
    remDr <- rD$client
    
    remDr$navigate("http://user:passwd@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()
    

    或者,如果这不起作用,您可以设置自定义标题:

    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()
    

    【讨论】:

    • 很遗憾,它必须是 https。同时,我什至无法访问 url ......即使我完全忽略了用户/密码,并尝试导航到这个 https 站点,然后运行 ​​remDr$getCurrenturl() 我看到它仍然在大约:blank,即没有任何改变。
    • 尝试设置一个自定义标题,显然用实际替换user:passwd。如果这不起作用,则需要特定网站来进一步调查问题。
    • 没有骰子,很遗憾。仅出于我自己的理解,自定义标头的想法是通过对 $navigate() 的调用有效传递的吗?即,您编写上述代码的自定义标头将应用于任何基本的 http 授权弹出窗口?再次感谢您的帮助。
    • 是的,自定义标头已添加到导航调用中。如果您在给出的示例中省略自定义标头,您将看到身份验证不会发生。
    【解决方案2】:

    您可以通过使用getAllCookies 登录来使用cookie。然后,在 PhantomJS 浏览器中,调用addCookie

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-16
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      相关资源
      最近更新 更多