无法按名称和 XPath 在 Selenium WebDriver 中找到元素 [英] Unable to find element in Selenium WebDriver By Name and XPath

查看:35
本文介绍了无法按名称和 XPath 在 Selenium WebDriver 中找到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Selenium WebDriver 并编写了一个小代码来查找和元素(即按钮)并单击它.这是按钮的 HTML 代码:

I am working with Selenium WebDriver and wrote a small code to find and element (i.e a button) and click on it. Here is the HTML code for the button:

<input type="submit" name="j_id0:j_id2:j_id3:j_id4:j_id7" value="New Master Health Program" onclick="AddLink()" class="btn">

这是测试用例的 C# 代码:

Here is the C# code for the Test Case:

IWebElement newMasterHealthProgramsLink = driver.FindElement(By.Name("j_id0:j_id2:j_id3:j_id4:j_id7"));
newMasterHealthProgramsLink.Click();

我也尝试使用 XPath:

I tried using XPath as well:

IWebElement newMasterHealthProgramsLink = driver.FindElement(By.XPath("//input[@id='j_id0:j_id2:j_id3:j_id4:j_id5']"));
newMasterHealthProgramsLink.Click();

我找到了一个解决方案,说您一定没有实施 Wait for this.页面不会等待完全加载并尝试查找元素.所以我添加了等待命令,但没有发生任何有用的事情.仍然得到同样的错误:

I found a solution saying that you must not have implemented Wait for this. Page does not wait to load completely and tries to find the element. So I added wait command but nothing useful happened. Still getting the same error:

TestAutomation.Driver.Login:
OpenQA.Selenium.NoSuchElementException : The element could not be found

推荐答案

由于您的元素在 IFrame 中,您需要使用 WebDriver API '切换'到该 IFrame.

Since your element is in an IFrame, you'll need to 'switch' to that IFrameusing the WebDriver API.

默认情况下,Selenium 将使用顶部"框架,因此任何查找元素"查询都将定向到最顶部框架,并忽略任何子 IFrame.

By default, Selenium will use the 'top' frame, and therefore any 'find element' queries will be directed to the most top frame, and ignore any child IFrames.

为了解决这个问题,切换"到当前 IFrame 会指示 Selenium 将任何请求推送到该帧.

To solve this, 'switching' to the current IFrame directs Selenium to shove any requests to that frame instead.

driver.SwitchTo().Frame()

请注意,您需要通过 ID、索引(顶部帧为 0,下一帧为 1 等)或名称来访问该帧.

Note that you'll need a way of accessing the frame, either by it's ID, index (the top frame is 0, next frame down is 1, etc...) or name.

另一个注意事项是,任何进一步的请求都将被定向到该 IFrame,而忽略任何其他请求,包括顶部框架...因此,如果您需要访问顶部框架,则需要切换回:

Another note is that any further requests will be directed to that IFrame, ignoring any others, which includes the top one...so if you need to access the top frame, you'll need to switch back:

driver.Switch().DefaultContent().

这篇关于无法按名称和 XPath 在 Selenium WebDriver 中找到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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