我正在尝试使用Selenium来打开HTML页面并单击按钮。 我得到的HTML是:
<html>
<head>
<link rel="shortcut icon" type="image/x-icon">
<link rel="stylesheet" type="text/css" href="http://localhost:5050/style.css">
<title>Test</title>
</head>
<body>
<div class="btn-container">
<button class="btn-orange" id="successButton" name="Success" value="Success"> Success </button>
<button class="btn-orange" id="failButton" name="Fail" value="Fail"></button> Fail
</div>
</div>
<footer class="footer" align="center">
<div class="container-fluid">
<div class="clearfix">
<div class="cards pull-left">
</div>
</div>
</div>
</footer>
</body>
</html>
我正在尝试点击successButton
,但它似乎不起作用,我尝试通过其ID进行访问。
以下是我用于click
的行:
driver.findElement(By.id("successButton")).click();
这是我的全部功能:
public void openTheHtmlPageAndClickButton(
String pageUrl,
String SiteUrl,
String buttonValue) {
String lastUrl = null;
boolean timeout = true;
for (int tryNumber = 1; tryNumber <= 5 && timeout; tryNumber++) {
WebDriver driver = null;
try {
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), DesiredCapabilities.firefox());
System.out.println("Selenium open: " + pageUrl);
driver.get(pageUrl);
int i = 0;
Alert alert;
while (i++ < 30) {
try {
alert = driver.switchTo().alert();
if (alert != null) {
alert.accept();
}
} catch (NoAlertPresentException e) {
}
String currentUrl = driver.getCurrentUrl();
driver.findElement(By.id("successButton")).click();
if (!currentUrl.equals(lastUrl)) {
System.out.println("currentUrl: " + currentUrl);
lastUrl = currentUrl;
if (currentUrl.startsWith(SiteUrl)) {
timeout = false;
break;
}
} else {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
Assert.fail();
}
}
}
} catch (Exception e) {
System.out.println("Selenium exception: " + e.toString());
} finally {
if (driver == null) {
Assert.fail("Cannot open web driver, probably Selenium docker is down");
} else {
if (timeout) {
System.out.println("Page got timeout: page source: " + driver.getPageSource());
if (tryNumber == 5) {
Assert.fail("Page got timeout 3 times!!!");
}
}
driver.quit();
}
}
}
}
请告知我做错了什么。
答案 0 :(得分:0)
当我试图“点击”它时,显然没有出现按钮。稍微更改了超时并解决了问题。