NoSuchElementException:消息:没有这样的元素:尝试在 iframe 中查找元素时无法定位元素

NoSuchElementException: Message: no such element: Unable to locate element when trying to find element within a iframe

我正在尝试使用 Selenium 在 Python 中自动执行 Google Chrome 会话。到目前为止,我一直在使用扩展来获取 xpath,它工作正常。但是现在,我在使用我定位的xpath时遇到错误:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="ok"]"} (Session info: chrome=71.0.3578.98) (Driver info: chromedriver=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387),platform=Windows NT 6.3.9600 x86_64)

returns 错误的行如下所示:

browser.find_element_by_xpath('//*[@id="ok"]').click()

不幸的是,我需要点击的按钮在网页中很深,需要一定的插件,这让你很难复制我的程序流程。因此,我上传了网页源代码的图片(蓝线是我想点击的按钮):

您能否提供一些有关如何更正硒选择器的帮助,以便我能够单击该元素?

到所需元素上的 click(),因为所需元素在 <iframe> 内,因此您必须:

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

    • 代码块(使用CSS_SELECTOR):

      from selenium import webdriver
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      from selenium.webdriver.common.by import By
      
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#codefile_iframe")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#ok[value='OK'][onclick^='loginui']"))).click()
      
    • 代码块(使用 XPATH):

      from selenium import webdriver
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      from selenium.webdriver.common.by import By
      
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='codefile_iframe']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='ok' and @value='OK'][starts-with(@onclick,'loginui')]"))).click()
      

Here you can find a relevant discussion on

您需要先切换到 iframe,然后才能与其中的元素交互:

iframe = driver.find_element_by_id("codefile_iframe")    
driver.switch_to.frame(iframe)

然后继续等待点击