GVKun编程网logo

使用Java和Selenium WebDriver在表单和iframe中查找元素(javaweb获取表单数据)

28

最近很多小伙伴都在问使用Java和SeleniumWebDriver在表单和iframe中查找元素和javaweb获取表单数据这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展jav

最近很多小伙伴都在问使用Java和Selenium WebDriver在表单和iframe中查找元素javaweb获取表单数据这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展java – Selenium WebDriver:无法使用TinyMCE编辑器在iframe中找到元素、Java+selenium 之 WebDriver 常见特殊情况如 iframe / 弹窗处理 (四)、Java+selenium之WebDriver常见特殊情况如iframe/弹窗处理(四)、javascript – 如何使用Selenium WebDriver访问动态添加的iframe?等相关知识,下面开始了哦!

本文目录一览:

使用Java和Selenium WebDriver在表单和iframe中查找元素(javaweb获取表单数据)

使用Java和Selenium WebDriver在表单和iframe中查找元素(javaweb获取表单数据)

我正在尝试访问中存在的元素<form> <iFrame> <form> elements </form> </iFrame> </form>

您能帮助我访问这些与Selenium Webdriver和JAVA一起使用的 “元素” 吗?

遇到问题: 可以到达目标页面(存在上述元素),但是我的代码无法识别这些元素。

XML结构概述:

<body>    <form action="https://abcd/efgh/" name="outerForm" method="post" target="iFrameTitle">        <iframe width="700" height="600" src="" title="Frame for Java Test" name="iFrameTitle" scrolling="auto" frameborder="0">            <form id="innerFormID" name="innerForm" action="/xxx/xxxx/yyyy/zzzz/" method="post" autocomplete="off">                <fieldset id="ncDetailsInner">                    <div id="element1">                        <label for="label1">                        <abbr title="Required field">*</abbr></label>                        <input name="label2" type="text" maxlength="30" id="cardHolder" value="" >                    </div>                    <div id="element2">                        <label for="label3">Label3 <abbr title="Required field">*</abbr></label>                        <div id="element3">                            <label for="label4">Label4<abbr title="Required field">*</abbr></label>                            <input id="label5" name="labelname5" type="text" maxlength="19" value="">                        </div>                        <div id="element4">                            <label for="label6">Label6</label>                            <input id="label7" name="labelname7" type="text" size="2" maxlength="2" value=""disabled="">                        </div>                    </div>                </fieldset>            </form>        </iframe>    </form></body>

代码提取:

WebDriverWait wait_iframe = new WebDriverWait(driver, 20000);wait_iframe.until(ExpectedConditions.visibilityOfElementLocated((By.id("element2"))));calling_function(sh1.getCell(col + 10, row).getContents(),                 sh1.getCell(col + 11, row).getContents(),                sh1.getCell(col + 12, row).getContents(),                 sh1.getCell(col + 14, row).getContents());public static void called_funciton(String string1, String string2,        String string3, String string4) {        driver.findElement(By.name("Element1 Name")).sendKeys(string1);        driver.findElement(By.id("Element2 ID")).sendKeys(string2);        driver.findElement(By.id("Element3 ID")).sendKeys(string3);        driver.findElement(By.id("Element4 ID")).sendKeys(string4);        driver.findElement(By.name("submitButton")).click();    }

如果需要更多详细信息,请告诉我!

答案1

小编典典

在尝试在iframe中搜索元素之前,您必须将Selenium焦点切换到iframe。

在iframe中搜索元素之前,请尝试以下操作:

driver.switchTo().frame(driver.findElement(By.name("iFrameTitle")));

java – Selenium WebDriver:无法使用TinyMCE编辑器在iframe中找到元素

java – Selenium WebDriver:无法使用TinyMCE编辑器在iframe中找到元素

也许我的问题类似于这个 Selenium WebDriver cannot locate element within an iframe,and throws NoSuchElementException但是我仍然找不到必需的元素.
元素本身看起来:

body id="tinymce"contenteditable="true" onload="window.parent.tinyMCE.get('compose_295_composeEditor').onLoad.dispatch();" dir="ltr">

包含此元素的iframe是:

body id="tinymce"contenteditable="true" onload="window.parent.tinyMCE.get('compose_295_composeEditor').onLoad.dispatch();" dir="ltr">

我试过了

driver.switchTo().frame(10);
driver.switchTo().frame(driver.findElement(By.id("tinymce")));
driver.findElement(By.id("tinymce")).clear();
driver.findElement(By.id("tinymce")).sendKeys("Privet!"); // clear mail text body
driver.switchTo().defaultContent();

但收到错误:

Unable to locate frame: 10

尝试过类似的东西

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

如其他答案所述,但收到NoSuchElement错误.

元素周围的HTML是:

<div>
<div id="compose_295_toolbar_external">
<divhttps://www.jb51.cc/tag/dis/" target="_blank">display: none;">
<div id="compose_295_composeFrame">
<div></div>
<tablecellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div id="compose_295_composeEditorFrame">
<table id="compose_295_shell__text"cellspacing="0" cellpadding="0" bgcolor="" background="">
<tbody>
<tr>
<tr>
<td>
<table id="compose_295_middleTable"cellspacing="0" cellpadding="0">
<tbody>
<tr id="compose_295_middleRow_sht">
<td id="compose_295_shell__text_cell_holder"valign="top">
<tablecellspacing="0" cellpadding="0">
<tbody>
<tr>
<tr>
<td id="compose_295_shell__text_cell"valign="top">
<textarea id="compose_295_composeEditor"wrap="physical" tabindex="10" name="Body"https://www.jb51.cc/tag/dis/" target="_blank">display: none;" cols="80" rows="15" spellcheck="true" aria-hidden="true"> </textarea>
 <span id="compose_295_composeEditor_parent">
 <table id="compose_295_composeEditor_tbl"cellspacing="0" cellpadding="0">
<tbody>
<trhttps://www.jb51.cc/tag/irs/" target="_blank">irst mceLast">
<tdhttps://www.jb51.cc/tag/irs/" target="_blank">irst mceLast">
<iframe id="compose_295_composeEditor_ifr" frameborder="0" src="javascript:""" allowtransparency="true" title="{#aria.rich_text_area}"https://www.jb51.cc/tag/dis/" target="_blank">display: block;" hidefocus="true" tabindex="10" scrolling="auto">
<html>
<head xmlns="http://www.w3.org/1999/xhtml">
<body id="tinymce"contenteditable="true" onload="window.parent.tinyMCE.get('compose_295_composeEditor').onLoad.dispatch();" dir="ltr">
</html>
</iframe>
</td>
</tr>
</tbody>
</table>
</span>
</td>
</tr>
<tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>

UPD Selenium and wordpress: New post test,olyv的回答帮助了我,但是:
1)很难将这个问题与我的问题联系起来,因为它没有在标题中提到TinyMCE编辑器,而且问题不在于wordpress.
2)我编辑了我的问题名称来表明问题来源–TinyMCE编辑器.
3)Saifur的答案在这里完美地回答了我的问题.
所以我相信我的问题不应该被关闭

解决方法

根据html,识别iframe的选择器是不正确的.我正在使用一个cssSelector,它允许您识别具有部分id匹配的iframe.你为什么不尝试这个?

driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[id$='_composeEditor_ifr']")));
d̶r̶i̶v̶e̶r̶.̶s̶w̶i̶t̶c̶h̶T̶o̶(̶)̶.̶f̶r̶a̶m̶e̶(̶d̶r̶i̶v̶e̶r̶.̶f̶i̶n̶d̶E̶l̶e̶m̶e̶n̶t̶(̶B̶y̶.̶i̶d̶(̶"̶t̶i̶n̶y̶m̶c̶e̶"̶)̶)̶)̶;̶
driver.findElement(By.id("tinymce")).clear();
driver.findElement(By.id("tinymce")).sendKeys("Privet!"); // clear mail text body
driver.switchTo().defaultContent();

Java+selenium 之 WebDriver 常见特殊情况如 iframe / 弹窗处理 (四)

Java+selenium 之 WebDriver 常见特殊情况如 iframe / 弹窗处理 (四)

转自:https://www.cnblogs.com/andrew209/p/9017087.html

1. iframe 的处理

查找元素必须在对应的 ifarme 中查找,否则是找不到的

// 传入参数为 frame 的序号,从0开始
driver.switchTo().frame(Int index); 
// 传入参数为 frame 的 ID 或者 Name 属性 
driver.switchTo().frame(String nameOrId);
// 传入参数为 frameElement
driver.switchTo().frame(WebElement frameElement);
// 切换回父级 
driver.switchTo().defaultContent();

2. 弹出窗口的处理

// 只弹出一个窗口的情况 , 不需要传入任何参数 , 直接切换到下一个窗口
// 得到当前窗口的句柄
String currentWindow = driver.getWindowHandle(); 
// 得到所有窗口的句柄
Set<String> handles = driver.getWindowHandles(); 
Iterator<String> it = handles.iterator(); 
while (it.hasNext()) { 
    String handle = it.next(); 
    if (currentWindow.equals(handle)) 
        continue;
    WebDriver window = driver.switchTo().window(handle); 
    log.info("title,url = " + window.getTitle() + "," + window.getCurrentUrl()); 
 }
// 切换到指定的窗口, 遍历最多 10 次, 循环是为了提高稳定性, 个别浏览器下有的时候一次遍历找不到 ( String windowTitle ) 
for (int a = 0; a < =9; a++) { 
     Set<String> windowHandles = driver.getWindowHandles(); 
      for (String handler : windowHandles) { 
         driver.switchTo().window(handler); 
           String title = driver.getTitle(); 
           if (windowTitle.equals(title)) { 
            a = 10;  
            break;
           } 
      } 
}

3.  处理对话框 alert\confirm\prompt

   driver.switchTo ().alert () 可以得到 alert\confirm\prompt 对话框的对象,然后运用其方法对它进行操作。对话框操作的主要方法有:

  • getText () 得到它的文本值
  • accept () 相当于点击它的 "确认"
  • dismiss () 相当于点击 "取消" 或者叉掉对话框
  • sendKeys () 输入值,这个 alert\confirm 不能用,会报错

4. 富文本编辑器

1 // 富文本编辑框的处理 
2 driver.switchTo().frame("nameOrId"); // 定位到富文本输入框所在的 frame 
3 JavascriptExecutor js = (JavascriptExecutor) driver;   
4 js.executeScript("document.body.innerHTML=''ABCDEFG''"); // 通过 js 赋值进去

 

Java+selenium之WebDriver常见特殊情况如iframe/弹窗处理(四)

Java+selenium之WebDriver常见特殊情况如iframe/弹窗处理(四)

1. iframe 的处理

查找元素必须在对应的 ifarme 中查找,否则是找不到的

1 // 传入参数为 frame 的序号,从0开始
2 driver.switchTo().frame(Int index); 
3 // 传入参数为 frame 的 ID 或者 Name 属性 
4 driver.switchTo().frame(String nameOrId);
5 // 传入参数为 frameElement
6 driver.switchTo().frame(WebElement frameElement);
7 // 切换回父级 
8 driver.switchTo().defaultContent();

2. 弹出窗口的处理

 1 // 只弹出一个窗口的情况 , 不需要传入任何参数 , 直接切换到下一个窗口
 2 // 得到当前窗口的句柄
 3 String currentWindow = driver.getWindowHandle(); 
 4 // 得到所有窗口的句柄
 5 Set<String> handles = driver.getWindowHandles(); 
 6 Iterator<String> it = handles.iterator(); 
 7 while (it.hasNext()) { 
 8     String handle = it.next(); 
 9     if (currentWindow.equals(handle)) 
10         continue;
11     WebDriver window = driver.switchTo().window(handle); 
12     log.info("title,url = " + window.getTitle() + "," + window.getCurrentUrl()); 
13  }
 1 // 切换到指定的窗口, 遍历最多 10 次, 循环是为了提高稳定性, 个别浏览器下有的时候一次遍历找不到 ( String windowTitle ) 
 2 for (int a = 0; a < =9; a++) { 
 3      Set<String> windowHandles = driver.getWindowHandles(); 
 4       for (String handler : windowHandles) { 
 5          driver.switchTo().window(handler); 
 6            String title = driver.getTitle(); 
 7            if (windowTitle.equals(title)) { 
 8             a = 10;  
 9             break;
10            } 
11       } 
12 }

3.  处理对话框 alert\confirm\prompt

   driver.switchTo().alert()可以得到alert\confirm\prompt 对话框的对象,然后运用其方法对它进行操作。对话框操作的主要方法有:

  • getText() 得到它的文本值
  • accept() 相当于点击它的"确认"
  • dismiss() 相当于点击"取消"或者叉掉对话框
  • sendKeys() 输入值,这个 alert\confirm 不能用,会报错

4. 富文本编辑器

1 // 富文本编辑框的处理 
2 driver.switchTo().frame("nameOrId"); // 定位到富文本输入框所在的 frame 
3 JavascriptExecutor js = (JavascriptExecutor) driver;   
4 js.executeScript("document.body.innerHTML=''ABCDEFG''"); // 通过 js 赋值进去

 

javascript – 如何使用Selenium WebDriver访问动态添加的iframe?

javascript – 如何使用Selenium WebDriver访问动态添加的iframe?

我有一个没有iframe的页面,然后通过 JavaScript在点击一个锚点后添加一个iframe.

我遇到的问题是,当使用driver.switch_to_frame(x)切换到帧时,我仍然可以找到我的任何内容.

我已经尝试循环遍历使用driver.find_elements_by_tag_name(‘iframe’)找到的帧,并检查每个帧我期望找到的类,但没有这样的运气.

driver.switch_to_active_element()也没有给我正确的iframe.

我不确定iframe内容是否只是无法访问,因为JS DOM更改未反映在Selenium从驱动程序中看到的内容中.我已经为其他iframe完成了同样的过程而没有任何问题,但是这个只是不合作.以下是我正在处理的简化版本.

在JS之前:

<html>
    <body>
      <a onclick="jsmagic">load iframe</a>
    </body>
</html>

JS之后:

<html>
    <body>
      <iframe><div>Message</div></iframe>
      <a onclick="jsmagic">load iframe</a>
    </body>
</html>

Python WebDriver尝试:

driver.switch_to_frame(0)
driver.find_elements_by_class_name('modal')
driver.switch_to_default_content()

我也尝试了类似的变体:

frame = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to_frame(frame)
driver.find_elements_by_class_name('modal')

我曾尝试使用driver.execute_script来访问该对象,但获取内容超出了我的范围. Firefox控制台命令无法通过Selenium运行.

解决方法

这似乎是一个时间问题,我最终得到了以下几点:
def modal_must_show(self,string):
  for _ in range(12):
    for frame in self.driver.find_elements_by_tag_name('iframe'):
      try:
        if not frame.is_displayed():
          continue
        if frame.parent.page_source.find(string):
          return
      except:
        pass
  assert False,'Modal missing string'

今天的关于使用Java和Selenium WebDriver在表单和iframe中查找元素javaweb获取表单数据的分享已经结束,谢谢您的关注,如果想了解更多关于java – Selenium WebDriver:无法使用TinyMCE编辑器在iframe中找到元素、Java+selenium 之 WebDriver 常见特殊情况如 iframe / 弹窗处理 (四)、Java+selenium之WebDriver常见特殊情况如iframe/弹窗处理(四)、javascript – 如何使用Selenium WebDriver访问动态添加的iframe?的相关知识,请在本站进行查询。

本文标签: