Selenium 无法识别 iframe 中的 swagger web 元素

Selenium is unable to identify swagger web elements within an iframe

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

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>…</head>
27           <body class= “swagger-section” marginWidth= “0” marginheight= “0”>
                      <div class = “swagger-ui-wrap”>
                           <a id =”logo” href=http://swagger.io>swagger</a>
                                 …
                      </div>
80            </body>
81     </iframe>
82 </div>
83  ….

我已将以下 Maven 依赖项添加到我的 POM 中:

<!-- 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();

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>…</head>
27           <body class= “swagger-section” marginWidth= “0” marginheight= “0”>
              <div class = “swagger-ui-wrap”>
               <a id =”logo” href=http://swagger.io>swagger</a>
                 …
              </div>
80            </body>
81     </iframe>

<iframe>.


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

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

    • cssSelector:

      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();
      
    • xpath:

      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();
      

Here you can find a relevant discussion on