我正在尝试使用 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()
不幸的是,我需要单击的按钮位于网页的深处,并且需要某个插件,这使您很难复制我的程序流程。因此,我上传了网页源代码的图片(蓝线是我要点击的按钮):您能否就如何更正 Selenium 选择器提供一些帮助,以便我能够单击该元素?
最佳答案
致click()
在所需元素上,因为所需元素在 <iframe>
内所以你必须:
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()
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/