Search code examples
pythonseleniumif-statementinstagram

How to avoid unable to locate element with 'if' statement in Python (selenium)?


I'm accessing multiple instagram pages and clicking on 'following' boxes. Some accounts are private and the following/followers boxes aren't clickable. What i want to do is create a 'if' condition to avoid these unclickable situations. What I'm trying to do is coded below:

if driver.find_element_by_xpath('//div[@class="QlxVY"]/h2') == None:
      #do something (click on 'following' box and etc.)

This path above only exists in private account pages. It locates the "this account is private" phrase. So, my reasoning is: if the phrase do not appear, its because the account isn't private and i can keep going and click on the 'following' box. The problem is that the '==' operator followed by 'None' isn't working. When i reach a public account, i get the following error (my 'if' statement is ignored):

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //div[@class="QlxVY"]/h2

Am i using 'None' wrong? I need to use another thing? I already did some research and i didn't find clues about it... only posts talking about tips to locate a element that is previously hidden. Thank's!


Solution

  • You can try any one of these two methods:-

    1- By checking length of element

    element = driver.find_elements_by_xpath('//div[@class="QlxVY"]/h2')
    if len(element)==0:
        print('Element not Present ')
        #do something (click on 'following' box and etc.)
    

    2- By catching NoSuchElementException

    from selenium.common.exceptions import NoSuchElementException
    
    try:
        if driver.find_element_by_xpath('//div[@class="QlxVY"]/h2'):
            print('Element found')
        
    except NoSuchElementException:
        print('Element not Present')
        #do something (click on 'following' box and etc.)