我正在尝试自动登录我使用的网站。我有一个 Python 脚本,可以成功查找并更新用户名和密码,但是当我尝试“单击”登录时,出现过时元素异常。
代码是:
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://waveleisure.gs-signature.cloud/Connect/mrmLogin.aspx")
driver.implicitly_wait(10)
elements = driver.find_elements(By.TAG_NAME, "input")
print(len(elements), " elements found")
for el in elements:
if el.accessible_name == "Email Address":
print("got email address")
el.send_keys("****@gmail.com")
elif el.accessible_name == "Password":
print("got password")
el.send_keys("****")
driver.implicitly_wait(10)
elements = driver.find_elements(By.TAG_NAME, "input")
for el in elements:
if el.accessible_name == "Login":
print("got login")
el.click()
运行上面的脚本给出:
DevTools listening on ws://127.0.0.1:52650/devtools/browser/09db5c0e-52e4-45a4-8499-f5703dde1f6e
10 elements found
got email address
got password
got login
Traceback (most recent call last):
File "C:\Workspace\Booking\WavesBooking.py", line 28, in <module>
if el.accessible_name == "Login":
^^^^^^^^^^^^^^^^^^
File "C:\Users\pete_\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\webelement.py", line 303, in accessible_name
return self._execute(Command.GET_ELEMENT_ARIA_LABEL)["value"]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\pete_\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\webelement.py", line 395, in _execute
return self._parent.execute(command, params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\pete_\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 354, in execute
self.error_handler.check_response(response)
File "C:\Users\pete_\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: stale element not found
(Session info: chrome=130.0.6723.92); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#stale-element-reference-exception
这个循环就是问题所在:
elements = driver.find_elements(By.TAG_NAME, "input")
for el in elements:
if el.accessible_name == "Login":
print("got login")
el.click()
第一次执行
el.click()
会导致加载新页面,因此 elements
中的剩余项目现在引用不再位于当前页面上的元素。