用脚本自动填写并提交工单

wen 实用脚本 3

本文目录导读:

用脚本自动填写并提交工单

  1. 基础示例
  2. 更高级的版本(带配置和数据文件)
  3. 使用说明
  4. 注意事项
  5. 处理验证码(如果需要)

我来为您提供一个自动填写并提交工单的Python脚本示例,这个脚本使用Selenium来模拟浏览器操作。

基础示例

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.support.ui import Select
import time
def auto_fill_ticket():
    # 初始化浏览器
    driver = webdriver.Chrome()  # 确保已安装chromedriver
    wait = WebDriverWait(driver, 10)
    try:
        # 1. 打开工单系统
        driver.get("https://example-ticket-system.com/login")
        # 2. 登录(如果需要)
        username = wait.until(EC.presence_of_element_located((By.ID, "username")))
        username.send_keys("your_username")
        password = driver.find_element(By.ID, "password")
        password.send_keys("your_password")
        login_btn = driver.find_element(By.ID, "login-btn")
        login_btn.click()
        # 等待登录完成
        time.sleep(2)
        # 3. 点击创建工单按钮
        create_ticket_btn = wait.until(
            EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), '创建工单')]"))
        )
        create_ticket_btn.click()
        # 4. 填写工单表单
        # 标题
        title_input = wait.until(EC.presence_of_element_located((By.ID, "title")))
        title_input.send_keys("自动创建的测试工单")
        # 描述
        description = driver.find_element(By.ID, "description")
        description.send_keys("这是通过自动化脚本创建的工单\n用于测试自动提交功能")
        # 优先级选择
        priority_select = Select(driver.find_element(By.ID, "priority"))
        priority_select.select_by_visible_text("普通")  # 或 '紧急', '高', '低'
        # 分类选择
        category_select = Select(driver.find_element(By.ID, "category"))
        category_select.select_by_visible_text("技术支持")
        # 上传附件(如果需要)
        try:
            file_input = driver.find_element(By.NAME, "attachment")
            file_input.send_keys("/path/to/your/file.txt")
        except:
            pass  # 无附件上传字段
        # 5. 提交工单
        submit_btn = driver.find_element(By.XPATH, "//button[@type='submit']")
        submit_btn.click()
        # 6. 验证提交成功
        success_msg = wait.until(
            EC.presence_of_element_located((By.CLASS_NAME, "success-message"))
        )
        print(f"工单提交成功: {success_msg.text}")
    except Exception as e:
        print(f"提交失败: {str(e)}")
        # 截图保存现场
        driver.save_screenshot("error_screenshot.png")
    finally:
        # 关闭浏览器
        driver.quit()
if __name__ == "__main__":
    auto_fill_ticket()

更高级的版本(带配置和数据文件)

配置文件 config.py

# 工单系统配置
LOGIN_URL = "https://example.com/login"
TICKET_URL = "https://example.com/tickets/new"
# 登录信息
USERNAME = "your_username"
PASSWORD = "your_password"
# 浏览器配置
BROWSER_TYPE = "chrome"  # chrome 或 firefox
HEADLESS = False  # 是否无头模式

数据文件 tickets_data.json

[
    {
        "title": "网络连接问题",
        "description": "办公室网络频繁断开,影响正常工作",
        "priority": "紧急",
        "category": "网络故障",
        "department": "技术部",
        "contact": "张三"
    },
    {
        "title": "软件安装请求",
        "description": "需要在电脑上安装Adobe Photoshop软件",
        "priority": "普通",
        "category": "软件安装",
        "department": "设计部",
        "contact": "李四"
    }
]

完整脚本 ticket_automation.py

import json
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.support.ui import Select
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
import config
import time
import logging
# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class TicketAutomation:
    def __init__(self):
        self.driver = None
        self.wait = None
        self.config = config
    def init_browser(self):
        """初始化浏览器"""
        if self.config.BROWSER_TYPE.lower() == "chrome":
            options = ChromeOptions()
            if self.config.HEADLESS:
                options.add_argument("--headless")
            self.driver = webdriver.Chrome(options=options)
        else:
            options = FirefoxOptions()
            if self.config.HEADLESS:
                options.add_argument("--headless")
            self.driver = webdriver.Firefox(options=options)
        self.wait = WebDriverWait(self.driver, 10)
    def login(self):
        """登录系统"""
        try:
            self.driver.get(self.config.LOGIN_URL)
            # 填写登录信息
            username = self.wait.until(
                EC.presence_of_element_located((By.ID, "username"))
            )
            username.send_keys(self.config.USERNAME)
            password = self.driver.find_element(By.ID, "password")
            password.send_keys(self.config.PASSWORD)
            # 点击登录
            login_btn = self.driver.find_element(By.ID, "login-btn")
            login_btn.click()
            # 等待登录完成
            time.sleep(2)
            logger.info("登录成功")
            return True
        except Exception as e:
            logger.error(f"登录失败: {str(e)}")
            return False
    def create_ticket(self, ticket_data):
        """创建单个工单"""
        try:
            # 进入创建工单页面
            self.driver.get(self.config.TICKET_URL)
            # 填写标题
            title = self.wait.until(
                EC.presence_of_element_located((By.ID, "title"))
            )
            title.send_keys(ticket_data['title'])
            # 填写描述
            description = self.driver.find_element(By.ID, "description")
            description.send_keys(ticket_data['description'])
            # 选择优先级
            priority = Select(self.driver.find_element(By.ID, "priority"))
            priority.select_by_visible_text(ticket_data['priority'])
            # 选择分类
            category = Select(self.driver.find_element(By.ID, "category"))
            category.select_by_visible_text(ticket_data['category'])
            # 选择部门
            department = Select(self.driver.find_element(By.ID, "department"))
            department.select_by_visible_text(ticket_data['department'])
            # 填写联系人
            contact = self.driver.find_element(By.ID, "contact")
            contact.clear()
            contact.send_keys(ticket_data['contact'])
            # 提交
            submit_btn = self.driver.find_element(By.XPATH, "//button[@type='submit']")
            submit_btn.click()
            # 验证
            time.sleep(1)
            if "成功" in self.driver.page_source or "提交成功" in self.driver.page_source:
                logger.info(f"工单 [{ticket_data['title']}] 创建成功")
                return True
            else:
                logger.warning(f"工单 [{ticket_data['title']}] 可能创建失败")
                return False
        except Exception as e:
            logger.error(f"创建工单失败: {str(e)}")
            return False
    def batch_create_tickets(self, tickets_file="tickets_data.json"):
        """批量创建工单"""
        try:
            with open(tickets_file, 'r', encoding='utf-8') as f:
                tickets_data = json.load(f)
            success_count = 0
            total_count = len(tickets_data)
            for ticket in tickets_data:
                if self.create_ticket(ticket):
                    success_count += 1
                time.sleep(1)  # 避免请求过快
            logger.info(f"批量创建完成: 成功 {success_count}/{total_count}")
        except FileNotFoundError:
            logger.error(f"数据文件 {tickets_file} 不存在")
        except json.JSONDecodeError:
            logger.error(f"数据文件格式错误")
    def run(self):
        """运行自动化流程"""
        try:
            self.init_browser()
            if self.login():
                self.batch_create_tickets()
            else:
                logger.error("登录失败,无法继续")
        finally:
            if self.driver:
                self.driver.quit()
if __name__ == "__main__":
    auto = TicketAutomation()
    auto.run()

使用说明

安装依赖

pip install selenium

下载并安装浏览器驱动

运行脚本

python ticket_automation.py

注意事项

  1. 元素定位:根据实际页面修改HTML元素的ID、类名或XPath
  2. 等待时间:根据网络情况调整等待时间
  3. 反爬措施:某些系统可能有验证码或反自动化措施
  4. 隐私安全:不要将密码硬编码,建议使用环境变量
  5. 合规使用:确保自动化行为符合网站服务条款

处理验证码(如果需要)

def handle_captcha(self):
    """处理验证码(简化示例)"""
    try:
        # 方式1:等待手动输入
        input("请手动输入验证码后按回车...")
        # 方式2:使用OCR识别(需要安装tesserocr)
        # from PIL import Image
        # captcha_img = self.driver.find_element(By.ID, "captcha")
        # captcha_img.screenshot("captcha.png")
        # captcha_text = image_to_string(Image.open("captcha.png"))
        # captcha_input = self.driver.find_element(By.ID, "captcha-input")
        # captcha_input.send_keys(captcha_text)
    except Exception as e:
        logger.error(f"验证码处理失败: {str(e)}")

这个脚本提供了完整的自动化填写和提交工单的功能,您可以根据实际需求进行调整和扩展。

抱歉,评论功能暂时关闭!