我不断收到错误:无法定位元素:{“method”:“css选择器”,“selector”:“.user-profile-link”} - 除了此错误之外,一切正常,我尝试搜索没有成功的解决方案。请帮忙。请注意,在我粘贴的下面的代码中,我分别用“my_github_username”和“my_github_password”替换了我的真实用户名和密码。
from selenium import webdriver
from selenium.webdriver.common.by import 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()