Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Webdriver - NoSuchElementExceptions

I am using the python unit testing library (unittest) with selenium webdriver. I am trying to find an element by it's name. About half of the time, the tests throw a NoSuchElementException and the other time it does not throw the exception.

I was wondering if it had to do with the selenium webdriver not waiting long enough for the page to load.

like image 695
Gengar Avatar asked Nov 29 '22 13:11

Gengar


2 Answers

driver = webdriver.WhatEverBrowser()
driver.implicitly_wait(60) # This line will cause it to search for 60 seconds

it only needs to be inserted in your code once ( i usually do it right after creating webdriver object)

for example if your page for some reason takes 30 seconds to load ( buy a new server), and the element is one of the last things to show up on the page, it pretty much just keeps checking over and over and over again if the element is there for 60 seconds, THEN if it doesnt find it, it throws the exception.

also make sure your scope is correct, ie: if you are focused on a frame, and the element you are looking for is NOT in that frame, it will NOT find it.

like image 126
TehTris Avatar answered Dec 06 '22 19:12

TehTris


I see that too. What I do is just wait it out...

you could try:

while True:
    try:
        x = driver.find_by_name('some_name')
        break
    except NoSuchElementException:
        time.sleep(1)
        # possibly use driver.get() again if needed

Also, try updating your selenium to the newest version with pip install --update selenium

like image 44
eran Avatar answered Dec 06 '22 17:12

eran