2
\$\begingroup\$

I've written a Python script that randomly selects radio buttons for each question, and submits the google form. My main questions for improvement are:

  • Algorithm: I collect all the buttons into a 2D array, then use random.choice to select the radio buttons based on each nested array. I'm sure there's a better way to do this, since my algorithm is basically hard coded.
  • Performance: I know random.choice takes a lot more time than other methods, but it's the only way I know enough to write with it.
  • Wait Time: Right now, I wait .75 seconds before entering in another form. I'm wondering if there's a way to wait for the page to load completely, rather than wait and hope that it loads fast enough to not generate a page not found error.

script.py

#run with python3
from selenium import webdriver
import random
import time

#Setup paths and open chrome browser
chrome_path = "desktop/code/python/driver/chrome/chromedriver"
website_path = "https://docs.google.com/forms/d/e/1FAIpQLSdcWrIYQlNbywuLg276z0CbBw-GyQOj_s2ncR9qVA7F7FPARQ/viewform"
driver = webdriver.Chrome(chrome_path)
driver.get(website_path)

#Define options based on each section

#EXCEPT: 9 18 25 28 31 (for text areas)
options = [
    [0, 1, 2, 3],
    [4, 5, 6],
    [7, 8],
    [10, 11],
    [12, 13, 14, 15],
    [16, 17],
    [19, 20, 21],
    [22, 23, 24],
    [26, 27],
    [29, 30],
    [32, 33]
]

#Main loop
def main(counter):
    count = counter + 1

    #Collect all buttons on page and submit button
    buttons = driver.find_elements_by_xpath("//*[@class='freebirdFormviewerViewItemsRadioOptionContainer']")
    submit = driver.find_element_by_xpath("//*[@class='quantumWizButtonPaperbuttonLabel exportLabel']")

    """
    Randomly chooses an option from the 2D array based on what i is, and that
    number is the index of `buttons`, which the button in that index will be clicked
    """
    for i in range(len(options)):
        buttons[random.choice(options[i])].click()

    #Submit form
    submit.click()

    #Go to previous page, which will be the form
    driver.execute_script("window.history.go(-1)")

    #Output how many forms have been submitted thus far
    print(f"Form #{count} has been submitted!")

    #Wait for page to load again, then call main to run again
    time.sleep(.75)
    main(count)


if __name__ == '__main__':
    main(0)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.