Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python selenium not work with WebDriverWait

I try to login google with selenium. It work if I use sleep() like this code

browser = webdriver.Firefox()
browser.get('https://admin.google.com/')

emailElem = browser.find_element_by_id('Email')
emailElem.send_keys('mymail')
nextButton = browser.find_element_by_id('next')
nextButton.click()

sleep(5)
passwordElem = browser.find_element_by_id('Passwd')
passwordElem.send_keys('mypass')
signinButton = browser.find_element_by_id('signIn')
signinButton.click()

If I change sleep to WebDriverWait like this

browser = webdriver.Firefox()
browser.get('https://admin.google.com/')

emailElem = browser.find_element_by_id('Email')
emailElem.send_keys('mymail')
nextButton = browser.find_element_by_id('next')
nextButton.click()


passwordElem = WebDriverWait(browser, 5).until(
    EC.presence_of_element_located(browser.find_element_by_id('Passwd'))
)
passwordElem.send_keys('mypass')
signinButton = browser.find_element_by_id('signIn')
signinButton.click()

It show error like this .

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="Passwd"]

How to use WebDriverWait ?

like image 929
user572575 Avatar asked Jan 08 '17 08:01

user572575


2 Answers

Yes as Guy said, you browser.find_element_by_id('Passwd')) is not neccesary. Change to((By.ID, "Passwd"))) as shown in the documentation. Here's what the code should be:

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 

browser = webdriver.Firefox()
browser.get('https://admin.google.com/')

emailElem = browser.find_element_by_id('[email protected]')
emailElem.send_keys('youremail')
nextButton = browser.find_element_by_id('next')
nextButton.click()


passwordElem = WebDriverWait(browser,     5).until(EC.presence_of_element_located((By.ID, "Passwd")))

passwordElem.send_keys('yourpassword')
signinButton = browser.find_element_by_id('signIn')
signinButton.click()
like image 92
Vagif Avatar answered Nov 07 '22 12:11

Vagif


You don't need to use browser.find_element inside expected_conditions (that is why you get NoSuchElementException instead of TimeOutException). The correct way to use it is (By.ID, "id")

passwordElem = WebDriverWait(browser, 5).until(
    EC.presence_of_element_located((By.ID, "Passwd"))
)
like image 33
Guy Avatar answered Nov 07 '22 14:11

Guy