Selenium WebDriver无法在iframe中定位元素,并引发NoSuchElementException [英] Selenium WebDriver cannot locate element within an iframe, and throws NoSuchElementException

查看:223
本文介绍了Selenium WebDriver无法在iframe中定位元素,并引发NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这里有几个针对同一问题的查询,但没有一个为我的特定问题提供解决方案.

I realise there are several queries on here for this same problem but none of them provide a solution to my particular problem.

我正在运行一个Web驱动程序测试,该测试试图为邮件网站填写表单以根据地址详细信息查找邮政编码.尝试找到第一个文本框时,我一直收到此错误:

I am running a web driver test that tries to fill out a form for a mail website to find postcodes based on address details. I keep getting this error when trying to locate the first text box:

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"css selector","selector":"#ctl00_BodyContent_txtBuildingNumber"}

我已经使用xpath和id尝试查找元素,但是我一直收到错误消息.我可以看到在运行网络驱动程序时该元素存在,并且已经能够在页面上找到另一个文本元素并输入文本,但是对于该字段和框架中的其他字段,我一直收到此错误.

I have used xpath and the id to try and locate the element but I keep getting the error. I can see that this element is present when the webdriver is running and I have been able to locate another text element on the page and enter text, but I keep getting this error for this field and other fields within the frame.

我猜想问题一定与这个字段是iFrame的一部分有关.

I am guessing that the problem must be to do with the fact that this field is part of an iFrame.

我在测试中使用了隐式等待,但没有成功.我仍然会收到错误消息.

I have used implicit waits within the test but with no success. I still get the error.

推荐答案

根据声音,首先需要切换到包含要与之交互的元素的iframe元素. (尽管没有看到相关的HTML,但这只是一个推测).

By the sounds of it you'll need to first switch to the iframe element that contains the element that you want to interact with. (Although without seeing the relevant HTML this is a bit of an extrapolated guess).

driver.switchTo().frame();

例如:

driver.switchTo().frame(1);
driver.switchTo().frame(driver.findElement(By.id("id")));

与框架中的元素完成交互后,您需要切换回主页.

When you've finished interacting with the elements within the frame, you'll need to switch back to the main webpage.

driver.switchTo().defaultContent();

这篇关于Selenium WebDriver无法在iframe中定位元素,并引发NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆