【问题标题】:Unable to locate element in iFrame无法在 iFrame 中找到元素
【发布时间】:2019-12-11 22:09:37
【问题描述】:

我正在尝试获取某个按钮/框架的 xpath。我能够使用 xpath 定位元素,但是在运行自动化时,我得到 element not found 异常。我试图切换到特定的框架,然后找到按钮,但它不起作用。附加页面和图像的链接。 链接:https://www.msn.com/en-in/weather/today/New-Delhi,Delhi,India/we-city-28.608,77,201?iso=IN

这是我尝试过的代码。

WebDriverWait wait = new WebDriverWait(cdriver,30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='foot']//following::iframe[@style='width:9.7rem;']")));
System.out.println("Ive waited for the frame to load");
int size = cdriver.findElements(By.tagName("iframe")).size();
System.out.println(size);

/*for(int i=0; i<=size; i++){
cdriver.switchTo().frame(i);
System.out.println("Switched to frame "+i);
int total=  cdriver.findElements(By.xpath("//*[@id='u_0_0']/div/button/span")).size();
System.out.println(total);
cdriver.switchTo().defaultContent();
}*/

cdriver.switchTo().frame(2);
System.out.println("Switched to frame");

cdriver.findElement(By.xpath("//*[@id='u_0_0']/div/button/span")).click();

获取存在的帧数,然后检查每个元素,但它无法切换到帧。

【问题讨论】:

    标签: java selenium selenium-webdriver iframe


    【解决方案1】:

    当您使用switchTo().frame(2) 时,您实际上切换到了第三个&lt;iframe&gt;。您可以使用switchTo().frame(1),但更好的选择是使用唯一标识符而不是索引

    WebElement iframe = cdriver.findElement(By.csSelector("#fbcount > iframe"));
    cdriver.switchTo().frame(iframe);
    

    要等待帧加载使用frameToBeAvailableAndSwitchToIt,而不是elementToBeClickable

    wait.until(ExpectedConditions.elementToBeClickable(By.csSelector("#fbcount > iframe")));
    System.out.println("Switched to frame");
    

    【讨论】:

      【解决方案2】:

      要访问所需元素,因为所需元素位于 &lt;iframe&gt; 内,因此您必须:

      • 为所需的frameToBeAvailableAndSwitchToIt() 诱导 WebDriverWait
      • 您可以使用以下任一Locator Strategies

        • 使用CSS_SELECTOR

          driver.get("https://www.msn.com/en-in/weather/today/New-Delhi,Delhi,India/we-city-28.608,77,201?iso=IN")
          new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[src^='//www.facebook.com/plugins/like']")));
          
        • 使用XPATH

          driver.get("https://www.msn.com/en-in/weather/today/New-Delhi,Delhi,India/we-city-28.608,77,201?iso=IN")
          new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(@src, '//www.facebook.com/plugins/like')]")));
          

      在这里你可以找到Ways to deal with #document under iframe的相关讨论

      【讨论】:

      • 他使用的是 Java,而不是 Python。
      • @Guy 不错 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 2020-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      相关资源
      最近更新 更多