使用Selenium处理浏览器身份validation

有谁知道在自动化过程中使用Selenium或其他任何工具处理浏览器身份validation?

2015年编辑:

这个答案已经过时了。 WebDriver现在支持authentication! 请参阅如何使用Java处理Selenium WebDriver的身份validationpopup窗口


原始答案:

Selenium处理不好。


您可以尝试使用http://username:password@example.com/yourpage

而不只是http://example.com/yourpage

不过,据我所知,Firefox仍会popup一个浏览器对话框,要求确认。


如果您使用的是Java(或类似于AutoIt的工具),那么您可以尝试Robot 。


如果您使用WebDriver,则可以使用driver.manage().addCookie()


或者一个已经通过身份validation的自定义FirefoxProfile 。

我花了几天的时间在字面上。 尝试在我的公司networking中通过浏览器级别authentication来击中应用程序。 解决方法是在URL中使用“unsername:password @”组件, 但在loginURL的末尾添加正斜杠

所以总的loginURL看起来像这样(注意你的页面后的“/”):

HTTP://用户名:password@example.com/yourpage/

与Watir,水豚和Selenium Webdriver合作。

这是我在stackoverflow中的第一篇文章,我想破解我的关于浏览器身份validation的解决scheme。 我在网上阅读的一切都没有帮助我。 所以在提出请求之前,像这样:

 driver.get(url); 

你必须像这样运行一个新的线程:

 RunScript runScript = new RunScript(); runScript.start(); 

在这种情况下,您可以在另一个类的另一个线程上自由inputlogin名和密码

 public class RunScript extends Thread { @Override public void run() { try { File file = new File("D:\\jacob-1.18-x86.dll"); System.setProperty(LibraryLoader.JACOB_DLL_PATH, file.getAbsolutePath()); AutoItX autoIt = new AutoItX(); Thread.sleep(2000); autoIt.winActivate("yourWindowName", ""); autoIt.winWaitActive("yourWindowName"); if (autoIt.winExists("yourWindowName")) { autoIt.send("username{TAB}", false); autoIt.send("password{Enter}", false); } } } catch (InterruptedException ex) { // } } 

}

解决了这个问题。 而且非常稳定!

所有的黑客通过auto-it,sikuli等等,只是浪费你的时间,当你在CI解决scheme中运行它时,使用多种浏览器types/ OS /版本/解决scheme等。

正确的做法是识别authentication的实际方法,并使用Rest协议进行login。

我用它来获取JSESIONID cookie并将其插入到selenium驱动程序中。 提示:首先转到domian的非退出url,然后设置cookie,然后转到所需的url – 您已login。

使用:rest客户端authentication来获得JSESSION ID

并有了这些信息:

 browser().navigate(foo.getUrl()+"non-exiting-url"); //the information got from the rest client login: Cookie cookie = new Cookie(name, value, domain, path, expiry, isSecure, isHttpOnly); try { driver.manage().addCookie(cookie); } catch (Exception e) { System.out.println(e.toString()); } browser().navigate(foo.getUrl()); 

请享用!

您可以使用Firefox的Selenium 2 / Selenium WebDriver来使用Java Robot类

 WebDriver driver = new FirefoxDriver(); driver.get("http://localhost:9990"); WebElement myDynamicElement = driver.findElement(By.id("app")); Alert alert = driver.switchTo().alert(); try { Robot robot = new Robot(); alert.sendKeys("username"); robot.keyPress(KeyEvent.VK_TAB);//go to password feild robot.keyPress(KeyEvent.VK_P); robot.keyPress(KeyEvent.VK_A); robot.keyPress(KeyEvent.VK_S); robot.keyPress(KeyEvent.VK_S); robot.keyPress(KeyEvent.VK_ENTER); } catch (AWTException e) { e.printStackTrace(); } } 

用机器人使用selenium
http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Robot.html