Guy Montag Guy Montag -4 years ago 148
HTML Question

How to check if element is present before continuing using selenium and python?

How would I go about running a loop as long as a specific div-element is present on a website?

I need the parser to go through a number of pages and click next for each page - the last page is empty and thus lacks the aforementioned div-element, so I figured running this within a while-loop would be a good approach. I'm however not sure how I should make this properly.

What I currently have, though non-functioning, is:

test = driver.find_element_by_class_name("divClassName").size()


, and subsequently checking whether its size is
while(test != 0)
.

Any suggestions would be much appreciated!

Answer Source

Try to implement below approach:

from selenium.common.exceptions import NoSuchElementException    

while True:
    try:
        driver.find_element_by_class_name("divClassName")
        # do what you need
        # click "Next" button
    except NoSuchElementException:
        break

With above code you'll be able to get new page and perform actions if <div class="divClassName"> is found, and stops otherwise

Also note that size is a property of webelement, but not a method. You should use it as webelement.size instead of webelement.size()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download