Search code examples
pythonseleniumelementvisible

Check if text is visible with Selenium, Python


I am making a script that will fill the forms to create a Gmail account with Python. When a username is already used a message becomes visible. In dutch: "Dez gebruikersnaam worst al gebruikt. Probeer been andere gebruikersnaam." To be able to deal with this I need to detect when this message is visible, but I have no idea how to do that. If anyone can help, that would be amazing

enter image description here


Solution

  • Try this code:

    from selenium import webdriver
    import time
    
    path = '/home/avionerman/Documents/stack'
    driver = webdriver.Firefox(path)
    
    driver.get('https://www.google.com/intl/nl/gmail/about/#')
    
    try:
        print('locating create account button')
        create_account_button = driver.find_element_by_class_name('h-c-button')
    except:
        print("error, couldn't find create account button")
    try:
        create_account_button.click()
        print('navigating to creation page')
    except:
        print('error navigating to creation page')
    time.sleep(8)
    
    
    handles = driver.window_handles
    size = len(handles)
    
    driver.switch_to.window(handles[1])
    print(driver.title)
    
    
    
    first_name_input = driver.find_element_by_id('firstName')
    first_name_input.click()
    first_name_input.send_keys("WhateverYouWant")
    
    last_name_input = driver.find_element_by_id('lastName')
    last_name_input.click()
    last_name_input.send_keys("WhateverYouWant2")
    
    username_input = driver.find_element_by_id('username')
    username_input.click()
    username_input.send_keys('papadopoulos')
    
    pswd_input = driver.find_element_by_name('Passwd')
    pswd_input.click()
    pswd_input.send_keys('whateveryouwant')
    
    pswd_conf_input = driver.find_element_by_name('ConfirmPasswd')
    pswd_conf_input.click()
    pswd_conf_input.send_keys('whateveryouwant')
    
    next_button = driver.find_element_by_id("accountDetailsNext")
    next_button.click()
    
    
    # In the variable x I save the text that is included inside the specific xpath
    x = driver.find_element_by_xpath("//*[@id='view_container']/form/div[2]/div/div[1]/div[2]/div[1]/div/div[2]/div[2]/div").text
    print(x)
    
    # I assert in order to check if the variable x has the proper text value (the expected one)
    assert x == 'Dez gebruikersnaam worst al gebruikt. Probeer been andere gebruikersnaam.'
    
    
    time.sleep(10)
    

    In this way, if the assert passes mean that you see the warning message and in any other case the username for the mail is unique. So, the part of the code that I wrote to you, you can insert it inside if statements and you can handle it as you wish. If you need any further info feel free to ping me.