Python Selenium 自动化: 处理网页表单并输入随机分数
import os
import time
import random
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def check_browser():
'''检查是否已经打开了浏览器'''
try:
options = Options()
options.add_experimental_option('debuggerAddress', '127.0.0.1:9527')
browser = webdriver.Chrome(options=options)
browser.execute_script('return true')
return True
except:
return False
if __name__ == '__main__':
if not check_browser():
os.system(r'start chrome --remote-debugging-port=9527 --user-data-dir="D:\评阅用"')
options = Options()
options.add_experimental_option('debuggerAddress', '127.0.0.1:9527')
browser = webdriver.Chrome(options=options)
while True:
for handle in browser.window_handles:
browser.switch_to.window(handle)
if '内蒙古开放大学' in browser.title:
print('用户登录成功!')
break
else:
time.sleep(1)
continue
break
while True:
try:
# 使用 WebDriverWait 等待元素出现
score_box = WebDriverWait(browser, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, 'score-box'))
)
score_input = score_box.find_element_by_tag_name('input')
score_input.clear()
score_input.send_keys(str(random.randint(94, 99)))
time.sleep(1)
except:
time.sleep(1)
continue
这段代码实现了以下功能:
- 连接到已打开的浏览器: 代码首先检查是否已有一个浏览器实例在端口
9527上运行调试模式。如果没有,则启动一个新的 Chrome 实例并启用调试模式。 - 查找目标网页: 代码通过循环遍历浏览器窗口句柄,查找标题中包含 '内蒙古开放大学' 的页面。
- 定位并填写表单: 代码使用
WebDriverWait等待class属性为 'score-box' 的元素出现,然后找到其内部的input元素,清除其内容并填写一个 94 到 99 之间的随机整数。 - 循环执行: 代码会持续循环执行上述步骤,模拟用户不断填写分数的操作。
这段代码展示了如何使用 Python Selenium 进行简单的网页自动化操作,可以作为学习 Selenium 自动化测试和网页交互的入门示例。
原文地址: https://www.cveoy.top/t/topic/fYut 著作权归作者所有。请勿转载和采集!