这是我的程序,我试图点击忘记密码链接使用链接文本。
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
service_obj = Service("Downloads.exe")
driver = webdriver.Chrome(service =service_obj)
driver.get("https://rahulshettyacademy.com/client/auth/login")
driver.find_element(By.LINK_TEXT,"Forgot password?").click()
我正在努力达到忘记密码屏幕从登录屏幕使用自动化python与硒,但我得到下面的错误运行程序后。
Traceback (most recent call last):
File "C:Users938861PycharmProjectspythonProjectLocatorsextension.py", line 8, in <module>
driver.find_element(By.LINK_TEXT,"Forgot password?").click()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:Users938861PycharmProjectspythonProjectvenvLibsite-packagesseleniumwebdriverremotewebdriver.py", line 861, in find_element
return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:Users938861PycharmProjectspythonProjectvenvLibsite-packagesseleniumwebdriverremotewebdriver.py", line 444, in execute
self.error_handler.check_response(response)
File "C:Users938861PycharmProjectspythonProjectvenvLibsite-packagesseleniumwebdriverremoteerrorhandler.py", line 249, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"Forgot password?"}
(Session info: chrome=107.0.5304.107)
Stacktrace:
Backtrace:
Ordinal0 [0x0064ACD3+2075859]
Ordinal0 [0x005DEE61+1633889]
Ordinal0 [0x004DB7BD+571325]
Ordinal0 [0x0050AC2F+764975]
Ordinal0 [0x0050AE1B+765467]
Ordinal0 [0x0053D0F2+970994]
Ordinal0 [0x00527364+881508]
Ordinal0 [0x0053B56A+963946]
Ordinal0 [0x00527136+880950]
Ordinal0 [0x004FFEFD+720637]
Ordinal0 [0x00500F3F+724799]
GetHandleVerifier [0x008FEED2+2769538]
GetHandleVerifier [0x008F0D95+2711877]
GetHandleVerifier [0x006DA03A+521194]
GetHandleVerifier [0x006D8DA0+516432]
Ordinal0 [0x005E682C+1665068]
Ordinal0 [0x005EB128+1683752]
Ordinal0 [0x005EB215+1683989]
Ordinal0 [0x005F6484+1729668]
BaseThreadInitThunk [0x75C77D69+25]
RtlInitializeExceptionChain [0x7710BB9B+107]
RtlClearBits [0x7710BB1F+191]
Process finished with exit code 1
但是那个代码是不正确的。您需要考虑没有找到"忘记密码"链接的情况。根据文档,如果找不到元素,定位元素会引发异常。NoSuchElementException
是预期的。
您可以捕获该错误并实现自己的错误策略。可能是一个友好的消息和退出,如
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
import sys
service_obj = Service("Downloads.exe")
driver = webdriver.Chrome(service =service_obj)
driver.get("https://rahulshettyacademy.com/client/auth/login")
try:
driver.find_element(By.LINK_TEXT,"Forgot password?").click()
except NoSuchElementException:
print("Error: Could not find forgot password link", file=sys.stderr)
exit(2)