Home>

I am currently studying page migration using selenium.

Here are the error statements.
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:

I know the cause, but on the other hand I want to create an if statement that uses it.
That is,

if (for NoSuchElementException):
Move to another page

A program like

.

How can I do this?

  • Answer # 1

    It looks like this.

    from selenium.common.exceptions import NoSuchElementException
    try:
        # Code to find element
    except NoSuchElementException:
        # Code to move to another page

  • Answer # 2

    I am a beginner, but I often use try/except.

    # import library for exception handling
    from selenium.common.exceptions import NoSuchElementException
    try:
     The process you want to execute
    except NoSuchElementException:
     Processing when the above cannot be executed
     break
    # Example when using if statement:
    # Conditional branch with or without specific element
    if len (driver.find_elements_by_class_name ('hoge'))>0:
        print ('Yes')
    else:
        print ('No')

    I'm sorry if I didn't answer. . . . .

Related articles