Can't find any elements Selenium Python

Viewed 71

I'm trying to log in to a website using Selenium. My main problem is that I can't seem to find any of the elements relevant to logging in.

I just keep getting the NoSuchElementException error. I've tried researching but haven't had any luck figuring out why.

This is my code so far

from selenium import webdriver

driver = webdriver.Chrome("C:/path/to/chromedriver.exe")

driver.get('https://sports.dafabet.com/')

username = driver.find_element_by_id("userName")
password = driver.find_element_by_id("password")
login_button = driver.find_element_by_id("loginBtnForm")
2 Answers

You are missing a delay / wait before getting these elements.
The simplest way is to put some hardcoded sleep between the

driver.get('https://sports.dafabet.com/')

and

username = driver.find_element_by_id("userName")

like this:

driver.get('https://sports.dafabet.com/')
time.sleep(10)
username = driver.find_element_by_id("userName")

While much better practice is to use explicit wait, like this:

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

wait = WebDriverWait(driver, 30)
username = wait.until(EC.visibility_of_element_located((By.ID, 'userName')))

Try with ExplicitWaits

Code :

driver.maximize_window()
wait = WebDriverWait(driver, 10)
driver.get("https://www.dafabet.com/en/sports")
wait.until(EC.element_to_be_clickable((By.ID, "LoginForm_username"))).send_keys('your username')
wait.until(EC.element_to_be_clickable((By.ID, "LoginForm_password"))).send_keys('your password')
wait.until(EC.element_to_be_clickable((By.ID, "LoginForm_submit"))).click()

Imports :

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

Read more about ExplicitWait here - Official doc

Related