我有以下Selenium脚本用于在rediff.com上打开警报:
public class TestC {
public static void main(String[] args) throws InterruptedException, Exception {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//*[@id='signin_info']/a[1]")).click();
driver.findElement(By.id("btn_login")).click();
Thread.sleep(5000);
Alert alert=driver.switchTo().alert();
alert.accept();
}
}
这个相同的脚本在Firefox和IE9中运行良好,但是在打开警报后使用谷歌浏览器,其余代码无效。主要的是不显示任何异常,错误或任何东西。
请尽快提供任何解决方案。 非常感谢!
注意:如果我们需要更改浏览器或任何设置的任何设置,请告诉我。
Selenium version:Selenium(2) Webdriver
OS:Windows 7
Browser:Chrome
Browser version:26.0.1410.64 m
答案 0 :(得分:1)
我很确定你的问题很常见,这就是为什么我从不建议使用Thread.sleep()
,因为它不能保证代码只会在Alert
出现时运行,也就是它即使显示警报,也可能会增加测试时间。
下面的代码应该只等到页面上显示一些警告,我建议你使用这个Firefox和IE9。
public class TestC {
public static void main(String[] args) throws InterruptedException, Exception {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 5);
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//*[@id='signin_info']/a[1]")).click();
driver.findElement(By.id("btn_login")).click();
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
}
}
这里所做的大部分工作都在改变Thread.sleep()
,因为一个条件实际上只会在页面中出现alert()
时才在代码上前进。只要有人这样做,就会切换到它并接受。
您可以找到整个ExpectedConditions
课程here的Javadoc。
答案 1 :(得分:0)
不幸的是,C#API中不存在AlertIsPresent http://selenium.googlecode.com/git/docs/api/dotnet/index.html
您可以使用以下内容:
private static bool TryToAcceptAlert(this IWebDriver driver)
{
try
{
var alert = driver.SwitchTo().Alert();
alert.Accept();
return true;
}
catch (Exception)
{
return false;
}
}
public static void AcceptAlert(this IWebDriver driver, int timeOutInSeconds = ElementTimeout)
{
new WebDriverWait(driver, TimeSpan.FromSeconds(timeOutInSeconds)).Until(
delegate { return driver.TryToAcceptAlert(); }
);
}