Home > Software engineering >  I keep getting the error: Unable to locate element: {"method":"css selector",&qu
I keep getting the error: Unable to locate element: {"method":"css selector",&qu

Time:04-06

I keep getting the error: Unable to locate element: {"method":"css selector","selector":".user-profile-link"} - Everythin works Ok except for this error and I have tried to search for a solution with no success. Please help. Note that in the code I pasted below, I replaced my real username and password with "my_github_username" and "my_github_password" respectively.

enter code here 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()

CodePudding user response:

Can you print out the HTML by using the print(driver.page_source), so it is easier for people to help you investigate and you would get more efficient support?

I believe the potential root cause would be that the portion of your code gets executed before the element that you seek finishes loading. Perhaps, try adding time.sleep(5) or if you would want to be more advance, you can use 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()
  • Related