如何使用带有Java的Selenium WebDriver处理弹出窗口 [英] How to handle popup window using selenium webdriver with Java
问题描述
请帮助,我是Selenium的新手.我尝试使电子商务网站自动化,但在处理弹出窗口时遇到问题.这是场景:
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:
- 转到 http://www.lampsplus.com
- 单击标题部分中的销售"链接.
- 单击页面上显示的第一项/产品. (这将显示产品页面).
- 在产品页面上,单击红色的添加到购物车"按钮. (这会将产品添加到购物车并显示弹出窗口.)
- 在弹出窗口中,单击深灰色的继续购物"按钮. (这将关闭弹出窗口.)
- 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.)
我停留在第5步(错误消息:无法找到元素继续购物按钮") 这是步骤5之前的代码:
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
我知道.getWindowHandle();方法.我尝试了几种变体,但没有一个起作用. 谁能给我一个如何处理的想法.非常感谢!我使用Java.
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.
注意:我不是在LampsPlus工作,也不是在尝试推广他们的产品,该网站仅出于培训目的.
Note: I don't work for LampsPlus and not try to promote their products, this website was chosen for training purposes only.
推荐答案
元素aContinueShopping
包含在iframe中.
The element aContinueShopping
is contained within an iframe.
您必须使用以下方法切换到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();
iframe上没有'name'或'id',因此您必须使用WebElement或数字才能找到它.
There's no 'name' or 'id' on the iframe, so you'll have to use a WebElement or a numeric to find it.
使用完iframe后,您将使用以下方法切换回顶部":
Once you're done with that iframe, you'll switch back to 'top' by using:
d1.SwitchTo().DefaultContent();
这篇关于如何使用带有Java的Selenium WebDriver处理弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!