问题
I have a dropdown list, when I click on any of the dropdown value then a modal get opens, When I click outside the modal, it will get close. How to handle it with Selenium WebDriver?
here is my Modal Code
<div class="modal fade bd-example-modal-sm show" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" style="display: block;">
<div class="modal-dialog modal-sm">
<div class="modal-content">You click on Dropdown hover Option
</div>
</div>
I have tried with below code
driver.switchTo().defaultContent();
and
driver.switchTo().alert().dismiss();
But both are not working.
回答1:
If you don't want to hit the Esc key you can click on div that has been created to cover the rest of the page using the following:
driver.get("https://demo.stqatools.com/MouseHover.php");
WebElement hoverButton = driver.findElement(By.cssSelector(".dropbtn"));
WebElement linkOne = driver.findElement(By.cssSelector(".dropdown-content > a"));
//Activate modal dialogue
Actions action = new Actions(driver);
action.moveToElement(hoverButton).perform();
wait.until(ExpectedConditions.visibilityOf(linkOne));
action.moveToElement(linkOne).click().perform();
//Dismiss modal dialogue
driver.findElement(By.cssSelector(".show")).click();
回答2:
This is not an alert, it's just a normal piece of DOM which looks like a modal popup due to CSS styling
So all you need to do is to locate the element using, for instance it's text, the relevant XPath locator would be something like:
//div[contains(text(),'You click on Dropdown hover Option')]
It would be also good to "wait" until popup presence/intractability via WebDriverWait like:
new org.openqa.selenium.support.ui.WebDriverWait(driver, 10)
.until(
ExpectedConditions.elementToBeClickable(
By.xpath("//div[contains(text(),'You click on Dropdown hover Option')]")))
.click();
回答3:
The most easy way - it's click on some static text on page. Try click on page title (if exist).
来源:https://stackoverflow.com/questions/56734482/how-to-close-the-modal-using-selenium-webdriver