我正在使用Selenium网络驱动程序3.0,并希望从打开的两个对话框中点击活动对话框中的确定按钮(一个在后台,第二个在前台)。如何从html下面的父div中单击前景对话框确定按钮?我尝试使用nth-child和nth-of-type但是click总是找到第一个在后台显示的对话框,而web驱动程序无法点击OK按钮。
当我检查we.isDisplayed()然后它也找到第一个OK按钮,我想要we.isDisplayed()的方法用于第二个对话框OK按钮。
<div id="z_shell" class="DwtShell">
<div id="Dialog1" class="DwtDialog">
<td id="ErrorDialog_button1_title" class="ZWidgetTitle">OK</td>
<td id="ErrorDialog_button2_title" class="ZWidgetTitle">Cancel</td>
</div>
<div id="Dialog2" class="DwtDialog">
<td id="ErrorDialog_button2_title" class="ZWidgetTitle">OK</td>
</div>
</div>
注意:Dialog div id可以是任何内容,但类名是固定的:DwtDialog。
尝试过的代码:
WebDriver webDriver;
WebElement we = webDriver.findElement(By.cssSelector("div[class='DwtDialog']:nth-child(2) td[id$='_button2_title']:contains('OK')"));
visible = we.click();
// Click fails here
尝试定位器:
By.cssSelector("div[class='DwtDialog']:nth-child(2) td[id$='_button2_title']:contains('OK')")
By.xpath("//div[@class='DwtDialog'][2]//td[@id='ErrorDialog_button2_title' and contains(text(), 'OK')]")
By.xpath("//div[@id='z_shell']//div[@class='DwtDialog'][2]//td[@id='ErrorDialog_button2_title' and contains(text(), 'OK')]")
如何点击可见的对话框的确定按钮?大多数情况下,此对话框稍后加载。我的意思是nth-child(2)
和第三个对话nth-child(3)
作为提示。
答案 0 :(得分:1)
编辑:
我错过了关于id改变的评论......试试#2。我认为这样的事情应该有效,但我无法在没有页面的情况下进行测试。基本上,我们会抓取对话框td.ZWidgetTitle
上的所有按钮div.DwtDialog
。如果它可见并且包含&#34;确定&#34;,请单击它。
List<WebElement> dialogButtons = driver.findElements(By.cssSelector("div.DwtDialog > td.ZWidgetTitle"));
for (WebElement dialogButton : dialogButtons)
{
if (dialogButton.isDisplayed() && dialogButton.getText().equals("OK"))
{
dialogButton.click();
break;
}
}
编辑2:
获得更多信息后,这是另一种方法。很难弄清楚这些东西是否可以在没有访问网站的情况下工作,但如果它不起作用,这将有希望指向正确的方向。这将获得错误对话框上的所有OK按钮。问题是,哪一个是可点击的?我们可以吃掉当另一个元素收到点击时抛出的异常,直到我们发现一个不会抛出的东西......这是正确的。我做了一些本地测试,这段代码似乎对我有用。
List<WebElement> dialogButtons = driver.findElements(By.xpath("//td[starts-with(@id, 'ErrorDialog_button') and text()='OK']"));
System.out.println(dialogButtons.size());
System.out.println(dialogButtons.size());
for (WebElement dialogButton : dialogButtons)
{
try
{
dialogButton.click();
}
catch (WebDriverException e)
{
// do nothing
}
}