Repository navigation
Expand file tree
/
Copy pathiterate-agent.py
More file actions
171 lines (139 loc) · 6.86 KB
/
Copy pathiterate-agent.py
File metadata and controls
171 lines (139 loc) · 6.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import time
import random
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
def create_driver():
"""Create a Chrome WebDriver instance"""
chrome_options = Options()
# Hide automation features
chrome_options.add_argument('--start-maximized')
chrome_options.add_argument('--disable-blink-features=AutomationControlled')
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_options.add_experimental_option('useAutomationExtension', False)
# Uncomment the next line to run "invisibly" in the background
# chrome_options.add_argument('--headless')
driver = webdriver.Chrome(options=chrome_options)
return driver
def fill_form(driver):
"""Fill the form with random answers using dynamic UI handling"""
form_url = "https://docs.google.com/forms/#"
try:
print("Navigating to form URL...")
driver.get(form_url)
print("Waiting for page load...")
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "body")))
print("Page loaded. Initial wait for dynamic elements...")
time.sleep(3)
question_containers = driver.find_elements(By.CSS_SELECTOR, "div[role='listitem']")
print(f"Found {len(question_containers)} question containers.")
for i in range(len(question_containers)):
# Re-fetch containers each loop iteration in case DOM was dynamically updated
containers = driver.find_elements(By.CSS_SELECTOR, "div[role='listitem']")
if i >= len(containers):
break
container = containers[i]
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", container)
time.sleep(0.5)
choices = container.find_elements(By.CSS_SELECTOR, "[role='radio'], [role='checkbox']")
valid_choices = [c for c in choices if c.get_attribute("data-value") != "__other_option__"]
if not valid_choices:
texts = container.find_elements(By.CSS_SELECTOR, "input[type='text'], textarea")
if texts:
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", texts[0])
time.sleep(0.2)
try:
texts[0].send_keys("Test Answer")
except:
driver.execute_script("arguments[0].value = 'Test Answer';", texts[0])
continue
first_role = valid_choices[0].get_attribute("role")
def material_click(choice_el):
try:
# Imitate native keyboard click over material UI layers
choice_el.send_keys(Keys.SPACE)
except:
try:
# Fallback click the parent label container
label = choice_el.find_element(By.XPATH, "./ancestor::label")
driver.execute_script("arguments[0].click();", label)
except:
# Deep fallback raw JS click
driver.execute_script("arguments[0].click();", choice_el)
if first_role == 'checkbox':
num_to_click = random.randint(1, min(3, len(valid_choices)))
selected_choices = random.sample(valid_choices, num_to_click)
for choice in selected_choices:
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", choice)
time.sleep(0.2)
material_click(choice)
else:
choice = random.choice(valid_choices)
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", choice)
time.sleep(0.2)
material_click(choice)
time.sleep(0.2)
print("Scrolling to submit button...")
# Scroll completely down
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(1)
print("Finding and clicking submit button...")
submit_button = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//div[@role='button']//span[text()='Submit']/ancestor::div[@role='button'] | //div[@role='button'][@jsname='M2UYVd']"))
)
# Standard click logic for submit
try:
submit_button.click()
except:
driver.execute_script("arguments[0].click();", submit_button)
print("Waiting for submission confirmation...")
time.sleep(3)
try:
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Submit another"))
)
print("Submission successfully confirmed via completion screen.")
except:
print("Could not explicitly detect completion screen, but assuming submission went through.")
except Exception as e:
print(f"Form filling failed: {e}")
import traceback
traceback.print_exc()
def main():
"""Main function to run the bot for a specific number of times"""
driver = None
target_submissions = 10 # CHANGE THIS NUMBER to desired amount of forms to fill
completed_submissions = 0
try:
# Loop until we hit the target number
while completed_submissions < target_submissions:
try:
if driver is None:
driver = create_driver()
print("\n" + "="*50)
print(f"Starting form submission {completed_submissions + 1} of {target_submissions}...")
fill_form(driver)
completed_submissions += 1
if completed_submissions >= target_submissions:
print(f"\nSuccessfully reached target of {target_submissions} submissions. Stopping bot!")
break
# Random delay between submissions to appear more human
delay = random.uniform(5, 10)
print(f"Waiting {delay:.1f} seconds before next submission... (Press Ctrl+C to stop)")
time.sleep(delay)
except Exception as e:
print(f"Error during form submission loop: {e}")
if driver:
driver.quit()
driver = None
time.sleep(10) # Wait before retrying with a fresh driver
except KeyboardInterrupt:
print("\nBot stopped by user.")
finally:
if driver:
driver.quit()
if __name__ == "__main__":
main()