python-3.x - NoSuchElementException : Message: no such element: Unable to locate element when trying to find element within a iframe

标签 python-3.x selenium xpath css-selectors webdriverwait

我正在尝试使用 Selenium 在 Python 中自动执行 Google Chrome session 。到目前为止,我一直在使用扩展来获取 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)


返回错误的行如下所示:
browser.find_element_by_xpath('//*[@id="ok"]').click()
不幸的是,我需要单击的按钮位于网页的深处,并且需要某个插件,这使您很难复制我的程序流程。因此,我上传了网页源代码的图片(蓝线是我要点击的按钮):
enter image description here
您能否就如何更正 Selenium 选择器提供一些帮助,以便我能够单击该元素?

最佳答案

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 Ways to deal with #document under iframe

    关于python-3.x - NoSuchElementException : Message: no such element: Unable to locate element when trying to find element within a iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54180655/

    相关文章:

    python - 在 Python 中使用 "Decimal"

    python - Python如何传递多重继承的__init__参数

    firefox - 无法单击存在但不可见的输入类型 ="button"

    python - 如何使用Python从网页下载所有图像?

    python - 如何使用 python selenium 单击弹出窗口中的按钮?

    python - 将 json 数据写入 json 文件时 JSON.parse 错误

    python - 如何在执行 subprocess.Popen 时保留外壳上输出的原始颜色编码?

    使用 Selenium 的 Excel VBA

    perl - 如何使用XPath查询eXist?

    java - 这会通过标签名称 "c"获取元素吗?在我的程序中它不起作用?