I keep getting the error: Unable to locate element: {"method":"css selector","selector":".user-profile-link"}

I keep getting the error: Unable to locate element: {"method":"css selector","selector":".user-profile-link"}

我不断收到错误消息:无法定位元素:{"method":"css selector","selector":".user-profile-link"} - 一切正常好的,除了这个错误,我试图寻找一个没有成功的解决方案。请帮忙。请注意,在下面粘贴的代码中,我分别用“my_github_username”和“my_github_password”替换了我的真实用户名和密码。

在此处输入代码 从 selenium 导入 webdriver 从 selenium.webdriver.common.by 导入

browser = webdriver.Chrome()
browser.get("https://github.com/")


browser.maximize_window()
signin_link = browser.find_element(By.PARTIAL_LINK_TEXT, "Sign in")
signin_link.click()

username_box = browser.find_element(By.ID, "login_field")
username_box.send_keys("my_github_username")
password_box = browser.find_element(By.ID, "password")
password_box.send_keys("my_github_password")
password_box.submit()

profile_link = browser.find_element(By.CLASS_NAME, "user-profile-link")
link_label = profile_link.get_attribute("innerHTML")
assert "my_github_username" in link_label

browser.quit()

您能否使用 print(driver.page_source) 打印出 HTML,这样人们更容易帮助您进行调查,您会得到更有效的支持?

我认为潜在的根本原因是您的代码部分在您查找的元素完成加载之前执行。 也许,尝试添加 time.sleep(5) 或者如果你想更高级,你可以使用 WebDriverWait

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time


browser = webdriver.Chrome()
browser.get("https://github.com/")


browser.maximize_window()
signin_link = browser.find_element(By.PARTIAL_LINK_TEXT, "Sign in")
signin_link.click()

# add some wait time here by using either `time.sleep(5)` or WebDriverWait
# time.sleep(5)
wait = WebDriverWait(browser, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#login_field')))

username_box = browser.find_element(By.ID, "login_field")
username_box.send_keys("my_github_username")
password_box = browser.find_element(By.ID, "password")
password_box.send_keys("my_github_password")
password_box.submit()

# add some wait time here by using either `time.sleep(5)` or WebDriverWait
# time.sleep(5)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.user-profile-link')))

profile_link = browser.find_element(By.CLASS_NAME, "user-profile-link")
link_label = profile_link.get_attribute("innerHTML")
assert "my_github_username" in link_label

browser.quit()