问题
Please help, I'm new in Selenium. I try to automate eCommerce website and I have problem to handle popup window. Here is the scenario:
- Go to http://www.lampsplus.com
- Click on Sale link in the header section.
- Click on the 1st item/product displayed on the page. (This will show the product page).
- On the product page, click on the red Add To Cart button. (This will add a product to cart and display a popup).
- On the popup, click the dark-grey Continue Shopping button. (This will close the popup.)
I stuck on step 5 (Error message: Unable to locate element "Continue shopping button") Here is my code before step 5:
WebDriver d1 = new FirefoxDriver();
d1.manage().window().maximize();
d1.get("http://www.lampsplus.com");
d1.findElement(By.name("hdr_sale")).click();
d1.findElement(By.xpath(".//*[@id='sortResultContainer60238']/a[2]/span")).click();
d1.findElement(By.id("pdAddToCart")).click(); //This is step 4
//Here is suppose to be some code which handles the popup - my problem
d1.findElement(By.id("aContinueShopping")).click(); //This is step 5
I'm aware about .getWindowHandle(); method. I tried several variations of it and none of them worked. Can anyone give me an idea how to handle it. Many thanks! I use Java.
Note: I don't work for LampsPlus and not try to promote their products, this website was chosen for training purposes only.
回答1:
The element aContinueShopping
is contained within an iframe.
You'll have to switch to the iframe using:
WebElement frameID = d1.findElement(By.Css("#add-to-cart>iframe"));
d1.SwitchTo().Frame(frameID);
d1.findElement(By.id("aContinueShopping")).click();
There's no 'name' or 'id' on the iframe, so you'll have to use a WebElement or a numeric to find it.
Once you're done with that iframe, you'll switch back to 'top' by using:
d1.SwitchTo().DefaultContent();
来源:https://stackoverflow.com/questions/19694507/how-to-handle-popup-window-using-selenium-webdriver-with-java