切换到 iframe selenium 时出错 python

error switching to iframe selenium python

目前我正在尝试切换到 iframe/fancybox,但出现以下错误:

line 237, in check_response raise exception_class
(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: 
Message: unknown error: missing 'ELEMENT'

这就是我定位 iframe 的方式:

_iframe_ = {"by": By.XPATH, "value": "//iframe[@class='fancybox-iframe' and starts-with(@id,'fancybox-frame') and contains(@src,'/reminder/add/relation/')]"}


 def __init__(self, driver):
        super(BasePage, self).__init__()
        self.driver = drive
        self.driver.switch_to.frame(self._iframe_)

iframe 名称是:

fancybox-frame1518441842751" 

html:

  <iframe id="fancybox-frame1518443041369" name="fancybox-frame1518443041369" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" scrolling="auto" src="/reminder/add/relation/58048" kwframeid="1"></iframe>

要正确识别 <iframe>,您必须按如下方式更改 Locator Strategy

_iframe_ = {"by": By.XPATH, "value": "//iframe[@class='fancybox-iframe' and starts-with(@id,'fancybox-frame') and contains(@src,'/reminder/add/relation/')]"}

 def __init__(self, driver):
    super(BasePage, self).__init__()
    self.driver = driver
    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((self._iframe_)))

idname 属性看起来是动态的(代码中的数字与 html 不匹配)。你可以尝试通过部分id/name

定位
_iframe_ = {"by": By.CSS_SELECTOR, "value": "[id*='fancybox-frame']"}
# "[name*='fancybox-frame']"

作为旁注,frame() 可以接收 id/name 作为参数

self.driver.switch_to.frame('fancybox-frame1518441842751')

本来可以的(当然动态问题除外)。