TreeTrackerAutomator/app.py

73 lines
2.8 KiB
Python

import csv
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.firefox import GeckoDriverManager
# Set up the Firefox WebDriver using Service
service = Service(GeckoDriverManager().install()) # Automatically manage geckodriver
# Set up the Firefox options (you can use headless if you want)
options = webdriver.FirefoxOptions()
# Initialize the Firefox WebDriver with the correct Service and Options
driver = webdriver.Firefox(service=service, options=options)
# URL where the form is located
url = ""
# Open the webpage
driver.get(url)
# Wait until the page is loaded and the element is present
wait = WebDriverWait(driver, 10)
# Mapping of CSV values to radio button IDs
who_planted_the_trees_map = {
'individual': 'id25',
'organization': 'id27',
'professional': 'id29',
'municipality': 'id31',
'agency': 'id33'
}
# Read the CSV file
csv_file_path = "surveys/test.csv"
with open(csv_file_path, mode='r') as file:
surveys = csv.DictReader(file)
# Iterate through each survey in the CSV.
for survey in surveys:
# Get responses to qestions.
who_planted = survey['Who Planted The Tree(s)?'].lower()
start_date = survey['Start Date of Planting']
end_date = survey['End Date of Planting']
num_trees = survey['End Date of Planting']
# Answer the Who Planted The Tree(s)? question.
radio_button_id = who_planted_the_trees_map[who_planted]
try:
# Wait for the radio button to be clickable and click it
radio_button = wait.until(EC.element_to_be_clickable((By.ID, radio_button_id)))
radio_button.click()
except Exception as e:
print(f"Error selecting '{who_planted}' radio button (ID: {radio_button_id}): {e}")
# Click Next button.
driver.find_element(By.XPATH, '/html/body/div[3]/section[1]/div/div[6]/div[1]/button[2]').click()
# Answer the Start Date of Planting question.
radio_button_id = who_planted_the_trees_map[who_planted]
try:
# Wait for the radio button to be clickable and click it
radio_button = wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[3]/section[1]/div/div[6]/div[1]/button[2]')))
radio_button.click()
except Exception as e:
print(f"Error selecting '{who_planted}' radio button (ID: {radio_button_id}): {e}")
# Click Next button.
driver.find_element(By.XPATH, '/html/body/div[3]/section[1]/div/div[6]/div[1]/button[2]').click()
# Close the driver
driver.quit()