关于javascript:Selenium:如何在iframe中的div中输入文本

Selenium : How to enter text in div inside an iframe

HTML代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
     <iframe src="about:blank" style="height: 150px;">
           #document
                <html>
                   <head>
                       <body>
                            <button class="__clipped">
                                 
                                   ::after
                                 
                             </button>
                        </body>
                    </head>
              </html>
        </iframe>

我想在手动添加文本后在div.html中键入文本:

1
abcd

我尝试使用javascript输入文本:

1
2
JavascriptExecutor jse = (JavascriptExecutor)driver;
        jse.executeScript("document.evaluate('//div[@data-ghosttext="Add a detailed description here."]', document, null, 9, null).singleNodeValue.innerHTML="+""abc"");

但是它给了我错误:

org.openqa.selenium.JavascriptException: TypeError:
document.evaluate(...).singleNodeValue is null

我也尝试了切换到iframe,但是切换到iframe时无法识别div。另外,尝试执行以下命令时得到size=0。但是,当我检查元素时页面上有3个iframe。

1
 int size = driver.findElements(By.tagName("iframe")).size();

请问我能在Java / js中获得确切的命令吗?我可以使用它在div元素中键入内容。我使用testng处理硒框架


您必须首先切换到适当的frame,然后尝试按以下方式传递div中的任何文本:

1
driver.switchTo().frame(driver.findElement(By.xpath("//div[@class='listRte__editorFrame']//following::iframe[1]")));

But it gives me error: org.openqa.selenium.JavascriptException:
ReferenceError: abcd is not defined

abcd也需要用引号

1
2
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.evaluate('//html//body//div', document, null, 9, null).singleNodeValue.innerHTML="+"'abcd'");

或转义的双引号

1
2
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.evaluate('//html//body//div', document, null, 9, null).singleNodeValue.innerHTML="+""abcd"");

或简单地

1
jse.executeScript("document.querySelector( 'div' ).innerHTML =" +"'abcd'" );


要获取列表,请尝试:

1
2
List<WebElement> listFrames = driver.findElements(By.tagName("iframe"));
System.out.println("list frames  "+listFrames.size());

下一步切换到帧

1
driver.switchTo().frame(listFrames.get( frameIndex ));

,然后尝试输入该文本。