首页 > 解决方案 > Selenium 无法识别 iframe 中的 swagger Web 元素

问题描述

我有一些 selenium Web 驱动程序代码,无法识别第 23 行和第 81 行之间的任何 Web 元素。但是,我能够识别第 23 行以上和第 81 行以下的所有 Web 元素并与之交互。

19 ….
20 <div id="main" class="well content" ui-view="content">
21     <iframe src="swagger-ui/index.html" frameborder="0" marginheight="0" marginwidth="0"  
22      width="100%" height="900" scrolling="auto" target="_top" title="Swagger UI">
23           #document
24                <!doctype html>
25           <html>
26           <head>…&lt;/head>
27           <body class= “swagger-section” marginWidth= “0” marginheight= “0”&gt;
                      <div class = “swagger-ui-wrap”&gt;
                           <a id =”logo” href=http://swagger.io>swagger</a>
                                 …
                      </div>
80            </body>
81     </iframe>
82 </div>
83  ….

我在我的 POM 中添加了以下 maven 依赖项:

<!-- https://mvnrepository.com/artifact/io.swagger/swagger-core -->
<dependency>
   <groupId>io.swagger</groupId>
   <artifactId>swagger-core</artifactId>
   <version>1.5.21</version>
</dependency>

有人可以让我知道我是否需要在我的 POM 中包含其他依赖项,或者提供一些关于为什么 size = 0 在下面的语句中的见解?

size = driver.findElements(By.xpath("//*[@id='swagger-ui-container']")).size();

标签: seleniumxpathiframecss-selectorswebdriverwait

解决方案


SeleniumWebDriver无法将第 23 行和第 81 行之间的任何 Web 元素识别为这些行:

21     <iframe src="swagger-ui/index.html" frameborder="0" marginheight="0" marginwidth="0"  
22      width="100%" height="900" scrolling="auto" target="_top" title="Swagger UI">
23           #document
24                <!doctype html>
25           <html>
26           <head>…&lt;/head>
27           <body class= “swagger-section” marginWidth= “0” marginheight= “0”&gt;
              <div class = “swagger-ui-wrap”&gt;
               <a id =”logo” href=http://swagger.io>swagger</a>
                 …
              </div>
80            </body>
81     </iframe>

在一个<iframe>.


要识别标签中的所有 WebElement 并与之交互,<iframe>您必须:

  • 诱导WebDriverWait使所需的帧可用并切换到它
  • 诱导WebDriverWait使所需元素可见
  • 您可以使用以下任一解决方案:

    • 选择器

      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[title='Swagger UI'][src='swagger-ui/index.html']")));
      my_size = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("#swagger-ui-container"))).size();
      
    • 路径

      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@title='Swagger UI' and @src='swagger-ui/index.html']")));
      my_size = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@id='swagger-ui-container']"))).size();
      

在这里你可以找到关于如何在 iframe 下处理#document的相关讨论


推荐阅读