Metadata-Version: 2.4
Name: wjx-filler
Version: 1.0.0
Summary: 问卷星自动填写工具：通过 OpenAI 兼容协议请求 AI 获取答案并自动提交
Author: wjx-filler contributors
License-Expression: MIT
Keywords: wjx,questionnaire,openai,automation,survey
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: openai>=1.0.0
Requires-Dist: requests>=2.25
Requires-Dist: beautifulsoup4>=4.10
Requires-Dist: playwright>=1.40
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Dynamic: license-file

<div align="center">

# wjx-filler

**问卷星自动填写工具 · 通过 OpenAI 兼容协议请求 AI 获取答案**

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

</div>

---

## 简介

`wjx-filler` 是一个用于自动填写 [问卷星](https://www.wjx.cn/) 问卷的 Python 工具包。
它通过 **OpenAI 兼容协议** 调用大语言模型（LLM）为问卷题目生成自然、合理的答案，
然后自动填写并提交问卷。

支持任意 OpenAI 协议兼容的端点：OpenAI / DeepSeek / 通义千问 / 智谱 GLM / OneAPI / vLLM 等。

### 主要特性

- **多题型支持**：单选、多选、填空、多行填空、评分/量表、矩阵题
- **双模式提交**：
  - `browser` 模式（默认）：基于 Playwright 真实浏览器，可绕过阿里云行为验证
  - `http` 模式：纯 HTTP 请求，速度快，适用于未开启验证的问卷
- **OpenAI 兼容协议**：支持任意符合规范的 API 端点
- **JSON 输出强制**：自动启用 `response_format=json_object` 提升解析稳定性
- **CLI + 库**：可作为命令行工具使用，也可作为 Python 库嵌入

---

## 目录

- [安装](#安装)
- [快速开始](#快速开始)
- [使用示例](#使用示例)
- [作为 Python 库使用](#作为-python-库使用)
- [题型支持](#题型支持)
- [配置参考](#配置参考)
- [项目结构](#项目结构)
- [开发与测试](#开发与测试)
- [常见问题](#常见问题)
- [许可证](#许可证)

---

## 安装

### 通过 pip 安装

```bash
pip install wjx-filler
```

### 从源码安装

```bash
git clone <repo-url>
cd wjx-filler
pip install -e .
```

### 安装浏览器（启用 browser 模式必需）

`browser` 模式依赖 Playwright 的 Chromium 浏览器，安装后需单独下载：

```bash
playwright install chromium
```

> 💡 国内网络可设置镜像加速：
> ```bash
> PLAYWRIGHT_DOWNLOAD_HOST=https://cdn.npmmirror.com/binaries/playwright \
>     playwright install chromium
> ```

---

## 快速开始

### 命令行

```bash
# 用 AI 生成答案并提交（browser 模式，可过验证码）
wjx-filler https://ks.wjx.com/vm/r2E9Fg3.aspx \
    --api-key sk-xxx \
    --base-url https://api.deepseek.com/v1 \
    --model deepseek-chat

# 直接指定答案（不调 AI）
wjx-filler https://ks.wjx.com/vm/r2E9Fg3.aspx \
    --answers 1=Alex 2=2 3=2 4=3,4

# 先 dry-run 看解析与答案，不提交
wjx-filler <url> --api-key sk-xxx --dry-run

# 出现滑块验证码时手动完成（有头模式）
wjx-filler <url> --api-key sk-xxx --headed --manual-captcha

# 强制纯 HTTP 模式（不支持验证码）
wjx-filler <url> --api-key sk-xxx --mode http
```

### 兼容端点示例

| 服务商 | `--base-url` | `--model` |
|--------|--------------|-----------|
| OpenAI | `https://api.openai.com/v1` | `gpt-4o-mini` |
| DeepSeek | `https://api.deepseek.com/v1` | `deepseek-chat` |
| 通义千问 | `https://dashscope.aliyuncs.com/compatible-mode/v1` | `qwen-plus` |
| 智谱 GLM | `https://open.bigmodel.cn/api/paas/v4` | `glm-4-flash` |
| OneAPI | `http://localhost:3000/v1` | 自定义 |
| vLLM | `http://localhost:8000/v1` | 模型名 |

---

## 使用示例

### 示例 1：用 DeepSeek 自动填写

```bash
wjx-filler https://ks.wjx.com/vm/wXXXX.aspx \
    --api-key sk-xxxxxxxx \
    --base-url https://api.deepseek.com/v1 \
    --model deepseek-chat
```

### 示例 2：直接指定答案

不调用 AI，按 `题号=答案` 直接提交。多选用逗号分隔：

```bash
wjx-filler https://ks.wjx.com/vm/wXXXX.aspx \
    --answers 1=张三 2=2 3=男 4=A,B,C 5=8
```

### 示例 3：headless 模式后台运行

```bash
wjx-filler <url> --api-key sk-xxx --timeout 60
```

---

## 作为 Python 库使用

```python
import requests
from openai import OpenAI
from wjx_filler import (
    parse_questions,
    ask_ai,
    run_with_browser,
)

# 1. 抓取问卷页面
url = "https://ks.wjx.com/vm/wXXXX.aspx"
html = requests.get(url).text

# 2. 解析题目
questions = parse_questions(html)
print(f"解析到 {len(questions)} 道题")
for q in questions:
    print(q.qid, q.type, q.title, [o.text for o in q.options])

# 3. 调用 AI 获取答案
client = OpenAI(
    api_key="sk-xxx",
    base_url="https://api.deepseek.com/v1",
)
answers = ask_ai(client, "deepseek-chat", questions)
print("AI 答案:", answers)

# 4. 浏览器提交
result = run_with_browser(url, questions, answers, headless=True)
print("提交成功" if result.success else "提交失败")
print("最终 URL:", result.final_url)
```

### 纯 HTTP 提交（适用于未开启验证的问卷）

```python
from wjx_filler import fetch_page, submit_form, parse_questions, ask_ai
from bs4 import BeautifulSoup
from openai import OpenAI

session, html = fetch_page(url)
soup = BeautifulSoup(html, "html.parser")
questions = parse_questions(html)

client = OpenAI(api_key=..., base_url=...)
answers = ask_ai(client, "gpt-4o-mini", questions)

result = submit_form(session, url, soup, questions, answers)
print(result.success, result.status_code, result.body[:200])
```

---

## 题型支持

| 问卷星 type | 题型 | 解析 | 填写 | 提交 |
|------------|------|------|------|------|
| 1 | 单行填空 | ✅ | ✅ | ✅ |
| 2 | 多行填空 | ✅ | ✅ | ✅ |
| 3 | 单选 | ✅ | ✅ | ✅ |
| 4 | 多选 | ✅ | ✅ | ✅ |
| 5 / 11 | 量表/评分 | ✅ | ✅ | ✅ |
| 6 | 矩阵单选 | ✅ | ⚠️ | ⚠️ |
| 7 | 矩阵多选 | ✅ | ⚠️ | ⚠️ |
| 8 | 排序 | ✅ | ❌ | ❌ |
| 13 | 日期时间 | ✅ | ❌ | ❌ |
| 101 | 文件上传 | ✅ | ❌ | ❌ |

> ⚠️ 矩阵题解析已实现，但填写/提交部分为最佳努力，可能需要根据具体问卷结构微调。

---

## 配置参考

### CLI 参数

| 参数 | 说明 | 默认值 |
|------|------|--------|
| `url` | 问卷 URL（位置参数，必填） | - |
| `--api-key` | OpenAI 兼容 API key | - |
| `--base-url` | OpenAI 兼容协议 base URL | `https://api.openai.com/v1` |
| `--model` | 模型名称 | `gpt-4o-mini` |
| `--answers` | 直接指定答案（`题号=值`，多选用 `,`） | - |
| `--mode` | 提交模式：`browser` / `http` | `browser` |
| `--headed` | 显示浏览器窗口（调试用） | False |
| `--manual-captcha` | 出现验证码时手动完成 | False |
| `--dry-run` | 只解析与获取答案，不提交 | False |
| `--timeout` | 提交后等待结果秒数 | 60 |
| `--screenshot` | 失败截图保存路径 | `/tmp/wjx_result.png` |
| `--version` | 显示版本号 | - |

### 环境变量

- `OPENAI_API_KEY`：默认 API key（可选，CLI 优先用 `--api-key`）
- `HTTP_PROXY` / `HTTPS_PROXY`：HTTP 代理（沙箱/防火墙环境）
- `PLAYWRIGHT_DOWNLOAD_HOST`：Playwright 浏览器下载镜像

---

## 项目结构

```
wjx-filler/
├── pyproject.toml              # 包元数据与构建配置
├── README.md
├── LICENSE                     # MIT
├── .gitignore
├── wjx_filler/                 # 主包
│   ├── __init__.py             # 公共 API 导出
│   ├── __version__.py          # 版本信息
│   ├── constants.py            # 常量定义（请求头、题型映射等）
│   ├── parser.py               # 题目解析（Question / Option / parse_questions）
│   ├── ai_client.py            # OpenAI 兼容协议调用（ask_ai / build_prompt）
│   ├── http_submitter.py       # 纯 HTTP 提交（fetch_page / submit_form）
│   ├── browser_submitter.py    # 浏览器提交（run_with_browser）
│   └── cli.py                  # 命令行入口
└── tests/                      # 测试套件
    ├── __init__.py
    ├── conftest.py             # pytest fixture 与样本 HTML
    ├── test_parser.py
    ├── test_ai_client.py
    ├── test_http_submitter.py
    └── test_cli.py
```

---

## 开发与测试

### 开发环境

```bash
git clone <repo-url>
cd wjx-filler
pip install -e ".[dev]"
playwright install chromium
```

### 运行测试

```bash
# 运行全部测试
pytest

# 运行单个测试文件
pytest tests/test_parser.py

# 显示详细输出
pytest -v

# 生成覆盖率报告
pytest --cov=wjx_filler --cov-report=html
```

### 测试覆盖

- `test_parser.py`：题目解析（题号、题型、选项、必答、矩阵、空 HTML）
- `test_ai_client.py`：Prompt 构造、JSON 解析、模型兼容性、mock 调用
- `test_http_submitter.py`：表单字段构造、隐藏字段、多选 `$v$v$` 格式、提交结果
- `test_cli.py`：CLI 参数解析、答案构造、dry-run 流程

---

## 常见问题

### Q1: 提交后页面返回 "22"

问卷星返回码 `22` 表示缺少行为验证 token。该问卷启用了阿里云行为验证（`needLoadAliVerify=1`），
需使用 `browser` 模式（默认）通过浏览器执行 JS 完成无感验证。

### Q2: 阿里云验证出现滑块

无感验证通常浏览器自动通过。若出现滑块，加 `--headed --manual-captcha` 由人工完成：

```bash
wjx-filler <url> --api-key ... --headed --manual-captcha
```

### Q3: AI 返回不是 JSON

脚本已自动从 markdown 代码块、纯文本中提取 JSON。若仍失败，会抛出
`RuntimeError: AI 返回无法解析为 JSON`，可换用支持 `json_object` 模式的模型
（如 `gpt-4o-mini` / `deepseek-chat`）。

### Q4: 多选题答案格式

CLI 用 `--answers 4=A,B,C` 表示多选 ABC；库 API 用 `answers[4] = ["A", "B", "C"]`。
提交时会自动转为问卷星格式 `$v1$v2$v3$`。

### Q5: 如何避免被风控

- 不要短时间内对同一问卷提交多次
- 可调整 `temperature=0.7`（默认）让 AI 答案有变化
- 必要时切换 IP 或使用代理

---

## 法律与道德声明

本项目仅供**学习研究**与**已获授权的测试场景**使用。
使用者应遵守当地法律法规与问卷星服务条款，不得用于：
- 数据采集、刷票、刷量等违反平台规则的行为
- 干扰问卷统计真实性的活动
- 任何违法违规用途

使用本工具产生的任何后果由使用者自行承担，作者不承担任何责任。

---

## 许可证

[MIT License](LICENSE) © wjx-filler contributors
