代码:
driver = webdriver.Chrome()
driver.get("https://commercialisti.it/iscritti")
driver.implicitly_wait(10)
casella_testo = driver.find_element("id", "Cap")
错误:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="Cap"]"}
(Session info: chrome=122.0.6261.131); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception
Stacktrace:
html:
<input class="form-control" id="Cap" name="Cap" type="text" value="">
我不明白为什么它找不到“Cap”
如果您注意到所需元素的 HTML,它被包装在 IFRAME 内。见下图。
要与
IFRAME
中的任何元素交互,您需要先切换 IFRAME
中的驱动程序上下文,然后执行所需的操作。完成所有操作后,您就可以退出IFRAME
。
参考下面的工作代码:
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://commercialisti.it/iscritti')
driver.implicitly_wait(10)
# Below line with switch into the iframe
driver.switch_to.frame(driver.find_element(By.XPATH, "(//iframe)[1]"))
# Below 2 lines will locate the desired element and send text "text" into the textbox
casella_testo = driver.find_element("id", "Cap")
casella_testo.send_keys("test")
# Below line will come out of iframe context
driver.switch_to.default_content()
time.sleep(10)
结果: