Ashiente Ani
Ashiente Ani

Reputation: 61

How to make selenium wait until the element is found instead of using time.sleep()

Basically the tittle, i'm building a small script to automate some basic stuff. I've been using time.sleep() to make the software wait a little until everything is loaded, but is there a better way to do this??

I want the script to wait as long as necessary by itself to make things faster and more clean.

from selenium import webdriver

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import Select
import time
from tkinter import *


def cs_update():

    PATH = "C:\Program Files (x86)\chromedriver.exe"
    options = Options()
    options.headless = True



    driver = webdriver.Chrome(PATH,options = options) 
    driver.set_window_size(1920,1080)
    driver.minimize_window()

    user_email = e.get()
    user_password = e2.get()

    driver.get("https://www.compraensanjuan.com")
    time.sleep(3)


    link = driver.find_element_by_link_text("Mi cuenta")

    link.click()
    time.sleep(3)

    email = driver.find_element_by_name("email")

    email.send_keys(user_email)

    print("I sent the keys")

Upvotes: 4

Views: 2548

Answers (1)

Parolla
Parolla

Reputation: 407

This is how you can use ExplicitWait

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

driver.get("https://www.compraensanjuan.com")

timeout = 20 # set seconds to wait until TimeOutException raised
link = WebDriverWait(driver, timeout).until(EC.element_to_be_clickable((By.LINK_TEXT, "Mi cuenta")))

link.click()

email = WebDriverWait(driver, timeout).until(EC.presence_of_element_located((By.NAME, "email")))

Upvotes: 1

Related Questions