Home > other >  EC.presence_of_element_located Using a variable for the value
EC.presence_of_element_located Using a variable for the value

Time:04-01

I have the following line of code in my program which works fine:

element_present = EC.presence_of_element_located(By.ID, 'Group_Documents_139')

I need to change the searched string to use a variable. I tried the following:

uploadsStartString2 = 'Group_Documents_139'
element_present = EC.presence_of_element_located(By.ID, '{0}' .format(uploadsStartString2)) 

It does not work for some reason. Any help appreciated.

CodePudding user response:

To use the variable you need to use the proper format of WebDriverWait and you can use either of the following approaches:

  • Replacing the variable directly:

    uploadsStartString2 = 'Group_Documents_139'
    element_present = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, uploadsStartString2)))
    
  • Using %s:

    uploadsStartString2 = 'Group_Documents_139'
    element_present = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, "'%s'"% str(uploadsStartString2))))
    
  • Using format():

    uploadsStartString2 = 'Group_Documents_139'
    element_present = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, "'{}'".format(str(uploadsStartString2)))))
    
  • Using f-strings:

    element_present = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, f"{uploadsStartString2}")))
    
  • Related