在此处输入我正在尝试在 Py Charm 上使用 Selenium 4.16,我运行以下代码并收到错误消息:
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://opensource-demo.orangehrmlive.com/")
driver.find_element(By.NAME,"username").send_keys("Admin")
driver.find_element(By.NAME,"password").send_keys("admin123")
C:\Code\PythonSelenium\PythonSelenium\venv\Scripts\python.exe C:\Code\PythonSelenium\PythonSelenium\selenium\FirstTestCase.py
Traceback (most recent call last):
File "C:\Code\PythonSelenium\PythonSelenium\selenium\FirstTestCase.py", line 7, in <module>
driver.find_element(By.NAME,"username").send_keys("Admin")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Code\PythonSelenium\PythonSelenium\venv\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 742, in find_element
return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Code\PythonSelenium\PythonSelenium\venv\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 348, in execute
self.error_handler.check_response(response)
File "C:\Code\PythonSelenium\PythonSelenium\venv\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="username"]"}`
XPATH 是比 ID 更好的方法。我尝试过使用 XPATH 并且它对我有用。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://opensource-demo.orangehrmlive.com/")
wait = WebDriverWait(driver, 20)
# Wait for the username field to be present
username_field = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div[1]/div/div[1]/div/div[2]/div[2]/form/div[1]/div/div[2]/input')))
username_field.send_keys("Admin")
password_field = driver.find_element(By.XPATH, '//*[@id="app"]/div[1]/div/div[1]/div/div[2]/div[2]/form/div[2]/div/div[2]/input')
password_field.send_keys("admin123")
time.sleep(5)
# Assuming there's a login button with ID 'btnLogin'
login_button = driver.find_element(By.XPATH, '//*[@id="app"]/div[1]/div/div[1]/div/div[2]/div[2]/form/div[3]/button')
login_button.click()
time.sleep(20)