【问题标题】:Unable to use elements within iframe after switching切换后无法使用 iframe 中的元素
【发布时间】:2019-04-08 18:57:49
【问题描述】:

我正在使用以下语句切换到 iframe,但在最后的等待中,我找不到 web 元素。有没有人有什么建议?我在谷歌上搜索了大约一天,尝试了不同的技术。到目前为止都没有工作

WebDriver driver = DriverFactory.getWebDriver()
WebDriverWait wait = new WebDriverWait(driver, 15)
driver.switchTo().defaultContent()
WebElement iframe = driver.findElement(By.cssSelector(".b-iframe__iframe"))
driver.switchTo().frame(iframe)
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(
 'fieldset.radio-switch-group')))

图片下方 HTML 的屏幕截图

【问题讨论】:

  • 你得到NoSuchElementExceptionTimeoutException?发布堆栈跟踪。
  • 堆栈跟踪:org.openqa.selenium.TimeoutException:预期条件失败:等待 By.cssSelector 定位的元素的可见性:fieldset.radio-switch-group(尝试 15 秒) 500 MILLISECONDS 间隔)在 org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:82)
  • 如果我显式等待并执行 driver.findElement 然后我得到这个异常堆栈跟踪:org.openqa.selenium.NoSuchElementException:没有这样的元素:无法找到元素:{“method”:” id","selector":"PaymentPage"}。就像 switch 语句不起作用
  • 你能把代码从你的IDE复制过去吗?

标签: selenium xpath iframe css-selectors webdriverwait


【解决方案1】:

根据您共享的 HTML 来定位所需的 WebElement,您必须:

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

    • 使用cssSelector

      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe.b-iframe__iframe[src*='securetest']")));
      WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("fieldset.radio-switch-group#balance-type")));
      
    • 使用xpath

      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@class='b-iframe__iframe' and contains(@src,'securetest')]")));
      WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//fieldset[@class='radio-switch-group' and @id='balance-type']")));
      

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

【讨论】:

  • 谢谢我已经把代码放进去,但没有运气。它几乎就像开关不工作一样。我已经打印了 driver.pageSource ,它在切换后打印了整个 DOM。我以为我应该只获得 iframe?
  • @JoeBatt 检查<iframe> 是否嵌套在另一个<iframe> 中,并使用您的代码试验和错误堆栈跟踪更新问题。
猜你喜欢
  • 2022-10-22
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 2018-12-31
  • 1970-01-01
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多