How to handle popup window using selenium webdriver with Java

杀马特。学长 韩版系。学妹 提交于 2019-12-19 09:26:51

问题


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:

  1. Go to http://www.lampsplus.com
  2. Click on Sale link in the header section.
  3. Click on the 1st item/product displayed on the page. (This will show the product page).
  4. On the product page, click on the red Add To Cart button. (This will add a product to cart and display a popup).
  5. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!