-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
383 lines (327 loc) · 17.2 KB
/
main.py
File metadata and controls
383 lines (327 loc) · 17.2 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import json
import random
import time
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
class QuestionnaireAutomation:
def __init__(self, config_path=None):
"""初始化问卷自动填写类"""
print("开始初始化...")
self.config = None
if config_path and os.path.exists(config_path):
self.load_config(config_path)
# 设置Chrome选项
print("配置Chrome选项...")
chrome_options = Options()
# 建议启用无头模式进行测试
#chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
# 初始化浏览器
print("正在启动Chrome浏览器...")
try:
driver_path = 'chromedriver.exe'
self.driver = webdriver.Chrome(
service=Service(driver_path),
options=chrome_options
)
print("Chrome浏览器启动成功!")
except Exception as e:
print(f"启动Chrome浏览器失败: {e}")
raise
self.wait = WebDriverWait(self.driver, 10)
def load_config(self, config_path):
"""加载配置文件"""
try:
with open(config_path, 'r', encoding='utf-8') as f:
self.config = json.load(f)
print(f"成功加载配置文件: {config_path}")
return True
except Exception as e:
print(f"加载配置文件失败: {e}")
return False
def fill_questionnaire(self):
"""填写整个问卷"""
if not self.config:
print("请先加载配置文件")
return False
try:
# 打开问卷网页
self.driver.get(self.config["url"])
print(f"已打开问卷链接: {self.config['url']}")
# 添加随机延迟,等待页面完全加载
time.sleep(random.uniform(2, 4))
# 处理"开始作答"按钮
if self.config.get("has_start_button", False):
try:
print("检查是否存在\"开始作答\"按钮...")
start_button = self.wait.until(
EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'slideChunkWord') and text()='开始作答']"))
)
print("找到\"开始作答\"按钮,准备点击...")
self.random_delay()
start_button.click()
print("已点击\"开始作答\"按钮")
# 等待页面加载
time.sleep(random.uniform(1, 2))
except Exception as e:
print(f"处理\"开始作答\"按钮时出错: {e}")
# 兼容新旧配置结构
if "pages" in self.config:
pages = self.config["pages"]
else:
# 旧版配置结构,将所有问题视为单页
pages = [{"questions": self.config["questions"]}]
# 填写多页问卷
for i, page in enumerate(pages):
print(f"开始填写第 {i+1} 页...")
# 填写当前页面的所有问题
for question in page["questions"]:
self.random_delay()
if question["type"] == "radio":
self.fill_radio_question(question)
elif question["type"] == "checkbox":
self.fill_checkbox_question(question)
elif question["type"] == "text":
self.fill_text_question(question)
else:
print(f"未知的问题类型: {question['type']}")
# 如果不是最后一页,点击"下一页"按钮
if i < len(pages) - 1:
self.random_delay()
try:
print("寻找\"下一页\"按钮...")
next_button = self.wait.until(
EC.element_to_be_clickable((By.XPATH, "//a[contains(@class, 'button') and contains(@onclick, 'show_next_page')]"))
)
print("找到\"下一页\"按钮,准备点击...")
next_button.click()
print("已点击\"下一页\"按钮")
time.sleep(random.uniform(1, 2)) # 等待页面加载
except Exception as e:
print(f"点击\"下一页\"按钮时出错: {e}")
break
self.random_delay()
# 使用更通用的提交按钮选择器,包括div元素
submit_xpath = self.config["submit"].get("xpath", "//div[@id='ctlNext' or contains(@class, 'submitbtn')]|//input[@type='submit' or @class='submitbutton']")
try:
print("寻找提交按钮...")
submit_button = self.wait.until(
EC.element_to_be_clickable((By.XPATH, submit_xpath))
)
print(f"找到提交按钮: {submit_button.tag_name} - {submit_button.text}")
# 尝试先滚动到按钮位置
self.driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", submit_button)
time.sleep(0.5)
# 使用JavaScript点击以避免可能的点击问题
self.driver.execute_script("arguments[0].click();", submit_button)
print("问卷已提交")
except Exception as e:
print(f"点击提交按钮时出错: {e}")
# 备用点击方法
try:
print("尝试使用备用方法找到提交按钮...")
all_buttons = self.driver.find_elements(By.XPATH, "//div[contains(@class, 'submitbtn') or contains(text(), '提交')]")
if all_buttons:
print(f"找到可能的提交按钮: {len(all_buttons)}个")
self.driver.execute_script("arguments[0].click();", all_buttons[0])
print("使用备用方法提交问卷")
except Exception as backup_error:
print(f"备用提交方法也失败: {backup_error}")
return False
# 等待提交完成
time.sleep(3)
print("本次填写完成")
return True
except Exception as e:
print(f"填写问卷时出错: {e}")
return False
def weighted_random_choice(self, options):
"""根据权重随机选择选项"""
weights = [option["weight"] for option in options]
total_weight = sum(weights)
# 归一化权重
normalized_weights = [w/total_weight for w in weights]
return random.choices(options, weights=normalized_weights, k=1)[0]
def fill_radio_question(self, question):
"""填写单选题"""
try:
container = self.wait.until(EC.presence_of_element_located((By.XPATH, question["xpath"])))
# 修改选项查找方式,匹配问卷星的实际HTML结构
options = container.find_elements(By.XPATH, ".//div[@class='label']")
# 如果找不到选项,尝试其他可能的选择器
if not options:
options = container.find_elements(By.XPATH, ".//label[contains(@for, 'q')]")
if not options:
options = container.find_elements(By.XPATH, ".//a[@class='jqradio']")
if options:
# 获取权重配置的选项
config_options = question["options"]
# 根据权重随机选择一个选项
selected_option = self.weighted_random_choice(config_options)
# 尝试找到匹配的选项并点击
found = False
for option_idx, option in enumerate(options):
option_text = option.text.strip()
if not option_text and option.get_attribute("class") == "jqradio":
# 如果是jqradio元素,它没有文本,尝试通过索引匹配
if option_idx < len(config_options):
self.driver.execute_script("arguments[0].click();", option)
found = True
print(f"问题{question['id']}: 选择了选项 {option_idx+1}")
break
elif selected_option["text"] in option_text or option_text in selected_option["text"]:
# 使用JavaScript点击以避免可能的元素被遮挡问题
self.driver.execute_script("arguments[0].click();", option)
found = True
print(f"问题{question['id']}: 选择了 '{selected_option['text']}'")
break
if not found:
# 如果没找到匹配的选项,随机选择一个
random_option = random.choice(options)
self.driver.execute_script("arguments[0].click();", random_option)
print(f"问题{question['id']}: 未找到配置的选项,随机选择了一个选项")
else:
# 尝试直接通过ID定位并点击input元素
try:
# 选择第一个选项
input_xpath = f"//div[@id='div{question['id']}']//input[contains(@id, 'q{question['id']}_')]"
inputs = self.driver.find_elements(By.XPATH, input_xpath)
if inputs:
selected_input = random.choice(inputs)
self.driver.execute_script("arguments[0].click();", selected_input)
print(f"问题{question['id']}: 通过input元素选择了一个选项")
return
except Exception as e:
pass
print(f"问题{question['id']}: 未找到选项")
except Exception as e:
print(f"填写问题{question['id']}时出错: {e}")
def fill_checkbox_question(self, question):
"""填写多选题"""
try:
container = self.wait.until(EC.presence_of_element_located((By.XPATH, question["xpath"])))
# 修改选项查找方式,匹配问卷星的实际HTML结构
options = container.find_elements(By.XPATH, ".//div[@class='label']")
# 如果找不到选项,尝试其他可能的选择器
if not options:
options = container.find_elements(By.XPATH, ".//label[contains(@for, 'q')]")
if not options:
options = container.find_elements(By.XPATH, ".//a[contains(@class, 'jqcheck')]")
if options:
# 获取权重配置的选项
config_options = question["options"]
# 确定要选择的选项数量
min_select = question.get("min_select", 1)
max_select = question.get("max_select", len(options))
max_select = min(max_select, len(options))
select_count = random.randint(min_select, max_select)
# 随机选择多个选项
selected_indices = random.sample(range(len(options)), select_count)
# 点击选中的选项
selected_count = 0
for idx in selected_indices:
option = options[idx]
try:
# 使用JavaScript点击以避免可能的元素被遮挡问题
self.driver.execute_script("arguments[0].click();", option)
self.random_delay(0.2, 0.5) # 短暂延迟,避免点击过快
selected_count += 1
option_text = option.text.strip() if option.text else f"选项{idx+1}"
print(f"问题{question['id']}: 选择了 '{option_text}'")
except Exception as e:
print(f"点击选项时出错: {e}")
if selected_count == 0:
# 如果没有选择任何选项,随机选择一个
random_option = random.choice(options)
self.driver.execute_script("arguments[0].click();", random_option)
print(f"问题{question['id']}: 备选方案随机选择了一个选项")
else:
# 尝试直接通过ID定位并点击input元素
try:
# 选择1-2个选项
input_xpath = f"//div[@id='div{question['id']}']//input[contains(@id, 'q{question['id']}_')]"
inputs = self.driver.find_elements(By.XPATH, input_xpath)
if inputs:
select_count = min(random.randint(1, 2), len(inputs))
selected_inputs = random.sample(inputs, select_count)
for input_elem in selected_inputs:
self.driver.execute_script("arguments[0].click();", input_elem)
self.random_delay(0.2, 0.5)
print(f"问题{question['id']}: 通过input元素选择了{select_count}个选项")
return
except Exception as e:
pass
print(f"问题{question['id']}: 未找到选项")
except Exception as e:
print(f"填写问题{question['id']}时出错: {e}")
def random_delay(self, min_time=None, max_time=None):
"""随机延迟,模拟人工操作"""
if min_time is None and max_time is None and self.config and "delay" in self.config:
min_time = self.config["delay"]["min_time"]
max_time = self.config["delay"]["max_time"]
else:
min_time = min_time or 0.5
max_time = max_time or 1.0
delay_time = random.uniform(min_time, max_time)
time.sleep(delay_time)
def fill_text_question(self, question):
"""填写填空题"""
text_field = self.wait.until(EC.presence_of_element_located((By.XPATH, question["xpath"])))
# 根据权重随机选择一个回答
selected_answer = self.weighted_random_choice(question["answers"])
# 模拟人工输入
for char in selected_answer["text"]:
text_field.send_keys(char)
time.sleep(random.uniform(0.05, 0.2))
print(f"问题{question['id']}: 输入了 '{selected_answer['text']}'")
def close(self):
"""关闭浏览器"""
if self.driver:
self.driver.quit()
print("浏览器已关闭")
def main():
# 初始化自动填写类
auto_wjx = QuestionnaireAutomation()
# 检查配置文件是否存在
config_path = "config.json"
if not os.path.exists(config_path):
print(f"请运行\"config_generator.py\",并编辑 {config_path} 文件后再运行程序")
auto_wjx.close()
return
# 加载配置文件
if auto_wjx.load_config(config_path):
# 获取重复次数
repeat_count = int(auto_wjx.config.get("repeat_count", 1))
print(f"计划填写问卷 {repeat_count} 次")
# 循环填写问卷
successful_count = 0
for i in range(repeat_count):
print(f"\n==== 开始第 {i+1}/{repeat_count} 次填写 ====")
# 每次填写前重新打开浏览器,避免cookie或其他状态影响
if i > 0:
auto_wjx.close()
auto_wjx = QuestionnaireAutomation()
auto_wjx.load_config(config_path)
success = auto_wjx.fill_questionnaire()
if success:
successful_count += 1
else:
print(f"第 {i+1} 次填写失败")
# 如果还有下一次填写,等待一段时间后再开始
if i < repeat_count - 1:
delay_time = random.uniform(5, 15)
print(f"等待 {delay_time:.1f} 秒后开始下一次填写...")
time.sleep(delay_time)
print(f"\n问卷填写完成,共成功填写 {successful_count}/{repeat_count} 次")
# 关闭浏览器
auto_wjx.close()
if __name__ == "__main__":
main()