Search code examples
pythonselenium

Python Selenium questions


So i'm trying to make an email checker too see if the email I want his username I want is taken, or isn't, but I cannot figure out how to do it

def check():
    if driver.find_element_by_xpath("""//*[@id="MemberNameError"]"""):
        print(user_input + " is taken")
    else:
        print("Success")
check()

Solution

  • It depends.

    If the element with id="MemberNameError" is only present in the DOM when there is a name error, you can try finding this element and handle the NoSuchElementException exception:

    from selenium.common.exceptions import NoSuchElementException
    
    def check():
        try:
            driver.find_element_by_xpath("""//*[@id="MemberNameError"]""")
            print(user_input + " is taken")
        except NoSuchElementException:
            print("Success")
    

    If the element becomes visible/invisible depending whether there is an error or not, check the element's "displayedness" via is_displayed() method:

    def check():
        error = driver.find_element_by_xpath("""//*[@id="MemberNameError"]""")
        if error.is_displayed():
            print(user_input + " is taken")
        else:
            print("Success")
    

    As a side note, there is a simpler find_element_by_id() locator - you don't have to use the XPath expressions always:

    driver.find_element_by_id("MemberNameError")