1

I have a function below that clicks the submit button on a form on my page. In order to successfully submit the form, a document must be attached. However, depending on how the database is linked sometimes, saved documents don't populate as already having been uploaded.

This is a minor detail, priority is to submit the form. I created an if statement, to check whether the upload button is present. If it is, then the it should upload a file from my computer, and then click the submit button. If its not, then it should just click the submit button.

This works, when the upload button is present. However, when its not, it gets stuck on the if condition and doesn't get to the else clause.


def submit_draw_request(driver, document_file_path):
    if EC.visibility_of_element_located((By.XPATH, "//button[text()='Upload']")):
        shared.upload_file_from_computer(driver, "//input[@class='MultipleFileUploadWidget']", document_file_path)
        time.sleep(2)
        shared.click_button(driver, elements.submit_button)
    else:
        time.sleep(2)
        shared.click_button(driver, elements.submit_button)

  • 1
    visibility_of_element_located doesn't return a boolean i believe. – DMart May 25 '21 at 14:24
  • https://www.selenium.dev/selenium/docs/api/py/_modules/selenium/webdriver/support/expected_conditions.html#invisibility_of_element_located – DMart May 25 '21 at 14:24

2 Answers2

1

Looks like you are missing to define the expected conditions timeout.
So it should be something like this:

wait = WebDriverWait(driver, 10)
def submit_draw_request(driver, document_file_path):
    if wait.until(EC.visibility_of_element_located((By.XPATH, "//button[text()='Upload']"))):
        shared.upload_file_from_computer(driver, "//input[@class='MultipleFileUploadWidget']", document_file_path)
        time.sleep(2)
        shared.click_button(driver, elements.submit_button)
    else:
        time.sleep(2)
        shared.click_button(driver, elements.submit_button)
Prophet
  • 32,350
  • 22
  • 54
  • 79
0

You can try using the try-except block in python. Also there are some imports to be done while using WebDriverWait and expected_conditions

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
try:
    wait.until(EC.visibility_of_element_located((By.XPATH, "//button[text()='Upload']")))
    shared.upload_file_from_computer(driver, "//input[@class='MultipleFileUploadWidget']", document_file_path)
    time.sleep(2)
    shared.click_button(driver, elements.submit_button)       

except:
    time.sleep(2)
    shared.click_button(driver, elements.submit_button)

The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.

Libin Thomas
  • 829
  • 9
  • 18