init
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
# ============ 客户端环境变量示例 ============
|
||||
# 复制本文件为 .env 并填写真实值:.env
|
||||
|
||||
# 云端服务端地址(部署后改成你的服务器地址)
|
||||
SERVER_URL=http://127.0.0.1:8000
|
||||
|
||||
# 本地控制面板端口
|
||||
WEB_PORT=8088
|
||||
|
||||
# AdsPower 本地 API(一般不用改)
|
||||
ADSPOWER_API_URL=http://local.adspower.net:50325
|
||||
# 你的 AdsPower Profile ID(在 AdsPower 界面查看,必填)
|
||||
ADSPOWER_USER_ID=
|
||||
|
||||
# AI 大模型(OpenAI 兼容接口)
|
||||
AI_BASE_URL=https://api.deepseek.com
|
||||
AI_MODEL=deepseek-chat
|
||||
AI_API_KEY=
|
||||
# 低于该分数的职位自动跳过
|
||||
AI_MIN_SCORE=65
|
||||
@@ -0,0 +1 @@
|
||||
"""客户端包"""
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
客户端 AI 大模型封装(OpenAI 兼容接口)
|
||||
功能:
|
||||
1. 职位匹配度评分
|
||||
2. 简历内容整理
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from openai import OpenAI
|
||||
from loguru import logger
|
||||
|
||||
from .config import client_settings
|
||||
|
||||
|
||||
class MatchResult:
|
||||
def __init__(self, score: int, reason: str):
|
||||
self.score = score
|
||||
self.reason = reason
|
||||
|
||||
def is_worth_applying(self, threshold: int = 60) -> bool:
|
||||
return self.score >= threshold
|
||||
|
||||
|
||||
class AIClient:
|
||||
"""OpenAI 兼容大模型客户端"""
|
||||
|
||||
def __init__(self, api_key: str | None = None, base_url: str | None = None,
|
||||
model: str | None = None):
|
||||
self.api_key = api_key or client_settings.AI_API_KEY or os.environ.get("AI_API_KEY", "")
|
||||
self.base_url = base_url or client_settings.AI_BASE_URL
|
||||
self.model = model or client_settings.AI_MODEL
|
||||
self.client = OpenAI(api_key=self.api_key, base_url=self.base_url)
|
||||
|
||||
def available(self) -> bool:
|
||||
return bool(self.api_key)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 职位匹配度评分
|
||||
# ------------------------------------------------------------------
|
||||
def score_job(self, jd_text: str, resume_content: str) -> MatchResult:
|
||||
"""根据 JD 与主简历内容评估匹配度"""
|
||||
if not self.available():
|
||||
return MatchResult(50, "AI 未配置,默认放行")
|
||||
|
||||
system_prompt = (
|
||||
"你是专业招聘顾问。根据职位描述(JD)和候选人简历,输出 JSON 评估结果,"
|
||||
"不要输出 JSON 以外的内容。\n"
|
||||
'格式:{"score": <0-100整数>, "reason": "<一句话评价>"}\n'
|
||||
"评分标准:80-100 高度匹配;60-79 基本匹配;40-59 部分匹配;0-39 不匹配。"
|
||||
)
|
||||
user_prompt = f"【职位描述】\n{jd_text}\n\n【候选人简历】\n{resume_content}"
|
||||
|
||||
try:
|
||||
resp = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=0.2,
|
||||
max_tokens=256,
|
||||
)
|
||||
raw = resp.choices[0].message.content.strip()
|
||||
if raw.startswith("```"):
|
||||
raw = raw.split("```")[1]
|
||||
if raw.startswith("json"):
|
||||
raw = raw[4:]
|
||||
data = json.loads(raw)
|
||||
return MatchResult(int(data.get("score", 50)), data.get("reason", ""))
|
||||
except Exception as e:
|
||||
logger.warning(f"AI 评分失败,默认放行:{e}")
|
||||
return MatchResult(50, f"AI 异常:{e}")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 简历内容整理
|
||||
# ------------------------------------------------------------------
|
||||
def clean_resume(self, raw_text: str) -> str:
|
||||
"""用 AI 将抓取的杂乱简历文本整理为清晰的结构化文本"""
|
||||
if not self.available():
|
||||
return raw_text
|
||||
|
||||
system_prompt = (
|
||||
"你是简历整理助手。将下面抓取的杂乱简历文本整理为清晰、结构化的纯文本简历,"
|
||||
"保留所有关键信息(姓名可省略,联系方式可保留),去除广告和无关内容。"
|
||||
"直接输出整理后的文本,不要加任何解释。"
|
||||
)
|
||||
try:
|
||||
resp = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": raw_text},
|
||||
],
|
||||
temperature=0.3,
|
||||
max_tokens=2048,
|
||||
)
|
||||
return resp.choices[0].message.content.strip()
|
||||
except Exception as e:
|
||||
logger.warning(f"AI 整理简历失败,返回原文:{e}")
|
||||
return raw_text
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 连通测试
|
||||
# ------------------------------------------------------------------
|
||||
def ping(self) -> bool:
|
||||
try:
|
||||
resp = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=[{"role": "user", "content": "回复1"}],
|
||||
max_tokens=5,
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"AI 接口连通失败:{e}")
|
||||
return False
|
||||
@@ -0,0 +1 @@
|
||||
"""浏览器自动化包"""
|
||||
@@ -0,0 +1,340 @@
|
||||
"""
|
||||
投递自动化模块
|
||||
在后台线程运行,支持用户随时开始/结束。
|
||||
向云端服务端上报投递记录与统计。
|
||||
"""
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from loguru import logger
|
||||
|
||||
from .manager import BrowserManager
|
||||
from ..ai import AIClient
|
||||
from ..server_api import ServerAPI
|
||||
|
||||
|
||||
@dataclass
|
||||
class JobCard:
|
||||
job_id: str
|
||||
title: str
|
||||
company: str
|
||||
salary: str
|
||||
location: str
|
||||
hr_active: str
|
||||
can_chat: bool
|
||||
can_deliver: bool
|
||||
jd_text: str = ""
|
||||
|
||||
|
||||
class Applicant:
|
||||
"""投递执行器(可启停)"""
|
||||
|
||||
BASE_URL = "https://www.zhipin.com"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
manager: BrowserManager,
|
||||
server_api: ServerAPI,
|
||||
ai_client: AIClient | None,
|
||||
):
|
||||
self.manager = manager
|
||||
self.server = server_api
|
||||
self.ai = ai_client
|
||||
|
||||
# 运行控制
|
||||
self._stop_event = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
self.is_running = False
|
||||
|
||||
# 运行时状态(供 Web 面板查询)
|
||||
self.session_id: int | None = None
|
||||
self.primary_resume_content: str = ""
|
||||
self.stats = {"applied": 0, "skipped": 0, "current": ""}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 启停控制
|
||||
# ------------------------------------------------------------------
|
||||
def start(self, keywords: list[str], city_code: str,
|
||||
salary_min: int | None, salary_max: int | None,
|
||||
greeting: str, min_score: int, delay_range: tuple[int, int]) -> None:
|
||||
"""在新线程中启动投递任务"""
|
||||
if self.is_running:
|
||||
logger.warning("已有投递任务在运行")
|
||||
return
|
||||
|
||||
# 创建服务端会话
|
||||
session = self.server.start_session(
|
||||
keywords=",".join(keywords),
|
||||
city_code=city_code,
|
||||
salary_min=salary_min,
|
||||
salary_max=salary_max,
|
||||
)
|
||||
self.session_id = session["id"]
|
||||
|
||||
# 获取主简历内容
|
||||
primary = self.server.get_primary_resume()
|
||||
self.primary_resume_content = primary["content"] if primary else ""
|
||||
|
||||
self._stop_event.clear()
|
||||
self.is_running = True
|
||||
self.stats = {"applied": 0, "skipped": 0, "current": "初始化..."}
|
||||
|
||||
self._thread = threading.Thread(
|
||||
target=self._run,
|
||||
args=(keywords, city_code, salary_min, salary_max,
|
||||
greeting, min_score, delay_range),
|
||||
daemon=True,
|
||||
)
|
||||
self._thread.start()
|
||||
logger.success(f"投递任务已启动,会话 ID:{self.session_id}")
|
||||
|
||||
def stop(self) -> None:
|
||||
"""请求停止投递任务"""
|
||||
logger.info("收到停止投递请求...")
|
||||
self._stop_event.set()
|
||||
|
||||
def _finish(self) -> None:
|
||||
"""任务结束后的收尾工作"""
|
||||
self.is_running = False
|
||||
if self.session_id:
|
||||
try:
|
||||
self.server.stop_session(self.session_id)
|
||||
except Exception as e:
|
||||
logger.warning(f"结束会话失败:{e}")
|
||||
self.stats["current"] = "已停止"
|
||||
logger.info(
|
||||
f"投递任务结束。本次投递 {self.stats['applied']} 个,"
|
||||
f"跳过 {self.stats['skipped']} 个"
|
||||
)
|
||||
|
||||
def _should_stop(self) -> bool:
|
||||
return self._stop_event.is_set()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 主循环
|
||||
# ------------------------------------------------------------------
|
||||
def _run(self, keywords, city_code, salary_min, salary_max,
|
||||
greeting, min_score, delay_range):
|
||||
try:
|
||||
for keyword in keywords:
|
||||
if self._should_stop():
|
||||
break
|
||||
self.stats["current"] = f"搜索关键词:{keyword}"
|
||||
self._process_keyword(
|
||||
keyword, city_code, salary_min, salary_max,
|
||||
greeting, min_score, delay_range,
|
||||
)
|
||||
if not self._should_stop():
|
||||
self._sleep(5, 9)
|
||||
except Exception as e:
|
||||
logger.error(f"投递任务异常:{e}")
|
||||
finally:
|
||||
self._finish()
|
||||
|
||||
def _process_keyword(self, keyword, city_code, salary_min, salary_max,
|
||||
greeting, min_score, delay_range, max_per_keyword: int = 15):
|
||||
page = 1
|
||||
applied_in_kw = 0
|
||||
while applied_in_kw < max_per_keyword and not self._should_stop():
|
||||
cards = self._fetch_job_list(keyword, city_code, salary_min, salary_max, page)
|
||||
if not cards:
|
||||
break
|
||||
for card in cards:
|
||||
if self._should_stop():
|
||||
return
|
||||
if applied_in_kw >= max_per_keyword:
|
||||
break
|
||||
applied_in_kw += self._handle_card(card, greeting, min_score, delay_range)
|
||||
page += 1
|
||||
|
||||
def _handle_card(self, card: JobCard, greeting: str, min_score: int,
|
||||
delay_range: tuple[int, int]) -> int:
|
||||
"""处理单个职位卡片,返回是否投递成功(1/0)"""
|
||||
# 1. 去重(服务端查询)
|
||||
try:
|
||||
if self.server.check_applied(card.job_id):
|
||||
return 0
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.stats["current"] = f"评估:{card.company} - {card.title}"
|
||||
|
||||
# 2. AI 匹配度评分
|
||||
ai_score, ai_reason = -1, ""
|
||||
if self.ai and self.ai.available() and self.primary_resume_content:
|
||||
jd = card.jd_text or self._fetch_jd_detail(card)
|
||||
result = self.ai.score_job(jd, self.primary_resume_content)
|
||||
ai_score, ai_reason = result.score, result.reason
|
||||
if not result.is_worth_applying(min_score):
|
||||
self._report_skip(card, f"AI 评分低({ai_score})", ai_score, ai_reason)
|
||||
return 0
|
||||
|
||||
# 3. 执行投递
|
||||
success, apply_type = self._apply(card, greeting)
|
||||
if success:
|
||||
self._report_apply(card, apply_type, ai_score, ai_reason)
|
||||
self._sleep(*delay_range)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 服务端上报
|
||||
# ------------------------------------------------------------------
|
||||
def _report_apply(self, card: JobCard, apply_type: str, ai_score: int, ai_reason: str):
|
||||
try:
|
||||
self.server.report_application(self.session_id, {
|
||||
"job_id": card.job_id,
|
||||
"job_title": card.title,
|
||||
"company": card.company,
|
||||
"salary": card.salary,
|
||||
"location": card.location,
|
||||
"apply_type": apply_type,
|
||||
"ai_score": ai_score,
|
||||
"ai_reason": ai_reason[:255] if ai_reason else None,
|
||||
})
|
||||
self.server.update_session_stats(self.session_id, applied_delta=1, skipped_delta=0)
|
||||
self.stats["applied"] += 1
|
||||
logger.success(f"[{self.stats['applied']}] 投递成功({apply_type}):{card.company} - {card.title}")
|
||||
except Exception as e:
|
||||
logger.warning(f"上报投递记录失败:{e}")
|
||||
|
||||
def _report_skip(self, card: JobCard, reason: str, ai_score: int = -1, ai_reason: str = ""):
|
||||
try:
|
||||
self.server.report_application(self.session_id, {
|
||||
"job_id": card.job_id,
|
||||
"job_title": card.title,
|
||||
"company": card.company,
|
||||
"salary": card.salary,
|
||||
"apply_type": "skipped",
|
||||
"ai_score": ai_score,
|
||||
"ai_reason": ai_reason[:255] if ai_reason else None,
|
||||
"skip_reason": reason,
|
||||
})
|
||||
self.server.update_session_stats(self.session_id, applied_delta=0, skipped_delta=1)
|
||||
self.stats["skipped"] += 1
|
||||
logger.info(f"跳过({reason}):{card.company} - {card.title}")
|
||||
except Exception as e:
|
||||
logger.debug(f"上报跳过记录失败:{e}")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 页面操作
|
||||
# ------------------------------------------------------------------
|
||||
def _fetch_job_list(self, keyword, city_code, salary_min, salary_max, page) -> list[JobCard]:
|
||||
page_obj = self.manager.ensure_connected()
|
||||
url = f"{self.BASE_URL}/web/geek/job?query={keyword}&city={city_code}&page={page}"
|
||||
if salary_min or salary_max:
|
||||
url += f"&salary={(salary_min or 0) * 1000},{(salary_max or 0) * 1000}"
|
||||
|
||||
self.stats["current"] = f"加载职位列表 第{page}页"
|
||||
try:
|
||||
page_obj.goto(url, wait_until="domcontentloaded", timeout=30000)
|
||||
page_obj.wait_for_timeout(2500)
|
||||
page_obj.wait_for_selector(".job-card-wrapper", timeout=10000)
|
||||
except Exception:
|
||||
logger.warning(f"第 {page} 页无职位列表")
|
||||
return []
|
||||
|
||||
cards = []
|
||||
for el in page_obj.query_selector_all(".job-card-wrapper"):
|
||||
try:
|
||||
card = self._parse_card(el)
|
||||
if card:
|
||||
cards.append(card)
|
||||
except Exception:
|
||||
continue
|
||||
logger.info(f"第 {page} 页解析到 {len(cards)} 个职位")
|
||||
return cards
|
||||
|
||||
def _parse_card(self, el) -> JobCard | None:
|
||||
def text(sel: str) -> str:
|
||||
node = el.query_selector(sel)
|
||||
return node.inner_text().strip() if node else ""
|
||||
|
||||
link = el.query_selector("a.job-card-left")
|
||||
href = link.get_attribute("href") if link else ""
|
||||
m = re.search(r"/job_detail/(\w+)\.html", href or "")
|
||||
if not m:
|
||||
return None
|
||||
return JobCard(
|
||||
job_id=m.group(1),
|
||||
title=text(".job-name"),
|
||||
company=text(".company-name"),
|
||||
salary=text(".salary"),
|
||||
location=text(".job-area"),
|
||||
hr_active=text(".info-public"),
|
||||
can_chat=bool(el.query_selector(".start-chat-btn:not([disabled])")),
|
||||
can_deliver=bool(el.query_selector(".btn-deliver")),
|
||||
)
|
||||
|
||||
def _fetch_jd_detail(self, card: JobCard) -> str:
|
||||
page_obj = self.manager.page
|
||||
try:
|
||||
page_obj.goto(f"{self.BASE_URL}/job_detail/{card.job_id}.html",
|
||||
wait_until="domcontentloaded", timeout=20000)
|
||||
page_obj.wait_for_timeout(1500)
|
||||
el = page_obj.query_selector(".job-detail-section")
|
||||
jd = el.inner_text().strip() if el else f"{card.title} {card.company}"
|
||||
page_obj.go_back()
|
||||
page_obj.wait_for_timeout(1500)
|
||||
return jd
|
||||
except Exception:
|
||||
return f"{card.title} {card.company}"
|
||||
|
||||
def _apply(self, card: JobCard, greeting: str) -> tuple[bool, str]:
|
||||
if card.can_chat and self._do_chat(card, greeting):
|
||||
return True, "chat"
|
||||
if card.can_deliver and self._do_deliver(card):
|
||||
return True, "deliver"
|
||||
return False, ""
|
||||
|
||||
def _do_chat(self, card: JobCard, greeting: str) -> bool:
|
||||
page_obj = self.manager.page
|
||||
try:
|
||||
btn = page_obj.query_selector(f"[data-job-id='{card.job_id}'] .start-chat-btn")
|
||||
if not btn:
|
||||
return False
|
||||
btn.click()
|
||||
page_obj.wait_for_timeout(2000)
|
||||
if greeting:
|
||||
inp = page_obj.query_selector(".chat-input textarea")
|
||||
if inp:
|
||||
inp.fill(greeting)
|
||||
page_obj.wait_for_timeout(500)
|
||||
send = page_obj.query_selector(".chat-input .btn-send")
|
||||
if send:
|
||||
send.click()
|
||||
page_obj.wait_for_timeout(1500)
|
||||
close = page_obj.query_selector(".dialog-container .close-btn")
|
||||
if close:
|
||||
close.click()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.debug(f"立即沟通失败:{e}")
|
||||
return False
|
||||
|
||||
def _do_deliver(self, card: JobCard) -> bool:
|
||||
page_obj = self.manager.page
|
||||
try:
|
||||
btn = page_obj.query_selector(f"[data-job-id='{card.job_id}'] .btn-deliver")
|
||||
if not btn:
|
||||
return False
|
||||
btn.click()
|
||||
page_obj.wait_for_timeout(2000)
|
||||
confirm = page_obj.query_selector(".dialog-confirm .btn-sure")
|
||||
if confirm:
|
||||
confirm.click()
|
||||
page_obj.wait_for_timeout(1500)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.debug(f"投递简历失败:{e}")
|
||||
return False
|
||||
|
||||
def _sleep(self, min_s: float, max_s: float) -> None:
|
||||
# 分段睡眠以便及时响应停止信号
|
||||
total = random.uniform(min_s, max_s)
|
||||
elapsed = 0.0
|
||||
while elapsed < total and not self._should_stop():
|
||||
time.sleep(0.5)
|
||||
elapsed += 0.5
|
||||
@@ -0,0 +1,154 @@
|
||||
"""
|
||||
浏览器管理器
|
||||
统一管理 AdsPower 浏览器启动与 Playwright CDP 连接。
|
||||
登录、抓取简历、投递共用同一个浏览器会话(复用登录态)。
|
||||
"""
|
||||
import requests
|
||||
from loguru import logger
|
||||
from playwright.sync_api import sync_playwright, Playwright, Browser, BrowserContext, Page
|
||||
|
||||
from ..config import client_settings
|
||||
|
||||
BOSS_HOME = "https://www.zhipin.com/web/geek/job"
|
||||
BOSS_RESUME_PAGE = "https://www.zhipin.com/web/geek/resume"
|
||||
|
||||
|
||||
class BrowserManager:
|
||||
"""管理 AdsPower 浏览器 + Playwright 连接"""
|
||||
|
||||
def __init__(self):
|
||||
self.api_url = client_settings.ADSPOWER_API_URL.rstrip("/")
|
||||
self.user_id = client_settings.ADSPOWER_USER_ID
|
||||
self._playwright: Playwright | None = None
|
||||
self._browser: Browser | None = None
|
||||
self._context: BrowserContext | None = None
|
||||
self.page: Page | None = None
|
||||
self.cdp_url: str | None = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# AdsPower 本地 API
|
||||
# ------------------------------------------------------------------
|
||||
def is_adspower_running(self) -> bool:
|
||||
try:
|
||||
resp = requests.get(f"{self.api_url}/status", timeout=5)
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def start_adspower_browser(self) -> str:
|
||||
"""启动 AdsPower 浏览器,返回 CDP 地址"""
|
||||
url = f"{self.api_url}/api/v1/browser/start"
|
||||
resp = requests.get(url, params={"user_id": self.user_id, "open_tabs": 1}, timeout=30)
|
||||
data = resp.json()
|
||||
if data.get("code") != 0:
|
||||
raise RuntimeError(f"启动 AdsPower 浏览器失败:{data.get('msg')}")
|
||||
ws = data["data"]["ws"]
|
||||
self.cdp_url = ws.get("puppeteer") or ws.get("selenium")
|
||||
logger.success(f"AdsPower 浏览器已启动,CDP: {self.cdp_url}")
|
||||
return self.cdp_url
|
||||
|
||||
def stop_adspower_browser(self) -> None:
|
||||
try:
|
||||
requests.get(
|
||||
f"{self.api_url}/api/v1/browser/stop",
|
||||
params={"user_id": self.user_id}, timeout=10,
|
||||
)
|
||||
logger.info("AdsPower 浏览器已关闭")
|
||||
except Exception as e:
|
||||
logger.warning(f"关闭 AdsPower 浏览器失败:{e}")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Playwright 连接
|
||||
# ------------------------------------------------------------------
|
||||
def connect(self) -> Page:
|
||||
"""启动浏览器并通过 CDP 连接,返回可操作的 page"""
|
||||
if self.page is not None:
|
||||
return self.page
|
||||
|
||||
if not self.user_id:
|
||||
raise RuntimeError("未配置 AdsPower Profile ID(ADSPOWER_USER_ID)")
|
||||
|
||||
if not self.is_adspower_running():
|
||||
raise RuntimeError("AdsPower 软件未运行,请先打开 AdsPower")
|
||||
|
||||
self.start_adspower_browser()
|
||||
self._playwright = sync_playwright().start()
|
||||
self._browser = self._playwright.chromium.connect_over_cdp(self.cdp_url)
|
||||
contexts = self._browser.contexts
|
||||
self._context = contexts[0] if contexts else self._browser.new_context()
|
||||
pages = self._context.pages
|
||||
self.page = pages[0] if pages else self._context.new_page()
|
||||
logger.info("Playwright 已连接到 AdsPower 浏览器")
|
||||
return self.page
|
||||
|
||||
def ensure_connected(self) -> Page:
|
||||
"""确保已连接,返回 page"""
|
||||
if self.page is None:
|
||||
return self.connect()
|
||||
return self.page
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 登录状态检测
|
||||
# ------------------------------------------------------------------
|
||||
def check_boss_login(self) -> bool:
|
||||
"""
|
||||
检测 Boss直聘 是否已登录。
|
||||
通过访问首页并检查是否存在登录后才有的元素判断。
|
||||
"""
|
||||
page = self.ensure_connected()
|
||||
try:
|
||||
page.goto(BOSS_HOME, wait_until="domcontentloaded", timeout=30000)
|
||||
page.wait_for_timeout(2000)
|
||||
# 已登录:页面上会显示用户头像/用户名;未登录:会显示"登录/注册"
|
||||
logged_in_indicators = [
|
||||
".user-nav .user-info",
|
||||
".nav-figure .user",
|
||||
"[class*='avatar']",
|
||||
".header-login .name",
|
||||
]
|
||||
for sel in logged_in_indicators:
|
||||
if page.query_selector(sel):
|
||||
logger.success("检测到已登录 Boss直聘")
|
||||
return True
|
||||
# 检查是否出现登录弹窗/登录按钮
|
||||
if page.query_selector(".btn-sign-up, .login-register, [class*='login-btn']"):
|
||||
return False
|
||||
# 兜底:检查 cookie 中是否有登录凭证
|
||||
cookies = page.context.cookies()
|
||||
cookie_names = {c["name"] for c in cookies}
|
||||
return "__zp_stoken__" in cookie_names or "wt2" in cookie_names
|
||||
except Exception as e:
|
||||
logger.warning(f"登录状态检测异常:{e}")
|
||||
return False
|
||||
|
||||
def get_boss_account_name(self) -> str | None:
|
||||
"""尝试获取登录用户名"""
|
||||
page = self.ensure_connected()
|
||||
try:
|
||||
for sel in [".user-nav .name", ".header-login .name", ".user-info .name"]:
|
||||
el = page.query_selector(sel)
|
||||
if el:
|
||||
return el.inner_text().strip()
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 关闭
|
||||
# ------------------------------------------------------------------
|
||||
def close(self) -> None:
|
||||
"""关闭 Playwright 连接(不关闭 AdsPower 浏览器,保留登录态)"""
|
||||
try:
|
||||
if self._playwright:
|
||||
self._playwright.stop()
|
||||
except Exception:
|
||||
pass
|
||||
self._playwright = None
|
||||
self._browser = None
|
||||
self._context = None
|
||||
self.page = None
|
||||
|
||||
def close_all(self) -> None:
|
||||
"""关闭连接并停止 AdsPower 浏览器"""
|
||||
self.close()
|
||||
self.stop_adspower_browser()
|
||||
@@ -0,0 +1,126 @@
|
||||
"""
|
||||
AI 简历抓取模块
|
||||
从已登录的 Boss直聘 账号中抓取所有简历,
|
||||
并用 AI 整理成结构化文本后返回。
|
||||
"""
|
||||
from loguru import logger
|
||||
|
||||
from .manager import BrowserManager, BOSS_RESUME_PAGE
|
||||
|
||||
|
||||
class ResumeScraper:
|
||||
"""抓取 Boss直聘 账号内的所有简历"""
|
||||
|
||||
def __init__(self, manager: BrowserManager, ai_client=None):
|
||||
self.manager = manager
|
||||
self.ai = ai_client
|
||||
|
||||
def scrape_all(self) -> list[dict]:
|
||||
"""
|
||||
抓取所有简历。
|
||||
返回格式:[{boss_resume_id, title, position, content}, ...]
|
||||
"""
|
||||
page = self.manager.ensure_connected()
|
||||
logger.info("正在打开 Boss直聘 简历页...")
|
||||
page.goto(BOSS_RESUME_PAGE, wait_until="domcontentloaded", timeout=30000)
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
resumes: list[dict] = []
|
||||
|
||||
# 尝试多种可能的简历卡片选择器(Boss直聘 页面结构可能变化)
|
||||
card_selectors = [
|
||||
".resume-item",
|
||||
".resume-card",
|
||||
"[class*='resume-list'] li",
|
||||
".geek-resume-item",
|
||||
]
|
||||
card_els = []
|
||||
for sel in card_selectors:
|
||||
card_els = page.query_selector_all(sel)
|
||||
if card_els:
|
||||
logger.info(f"使用选择器 {sel} 找到 {len(card_els)} 份简历")
|
||||
break
|
||||
|
||||
if not card_els:
|
||||
logger.warning("未通过卡片选择器找到简历,尝试整页抓取")
|
||||
return self._scrape_whole_page(page)
|
||||
|
||||
for i, card in enumerate(card_els):
|
||||
try:
|
||||
resume = self._parse_resume_card(card, i)
|
||||
if resume:
|
||||
resumes.append(resume)
|
||||
except Exception as e:
|
||||
logger.debug(f"解析第 {i} 份简历失败:{e}")
|
||||
|
||||
logger.success(f"共抓取到 {len(resumes)} 份简历")
|
||||
return resumes
|
||||
|
||||
def _parse_resume_card(self, card, index: int) -> dict | None:
|
||||
"""解析单个简历卡片"""
|
||||
def text(sel: str) -> str:
|
||||
el = card.query_selector(sel)
|
||||
return el.inner_text().strip() if el else ""
|
||||
|
||||
title = (
|
||||
text(".resume-title") or text(".title") or
|
||||
text(".name") or f"简历 {index + 1}"
|
||||
)
|
||||
position = text(".position") or text(".job-name") or text(".expect-position")
|
||||
|
||||
# 尝试点开详情获取完整内容
|
||||
content = self._extract_detail_content(card) or text(".resume-content") or text("p")
|
||||
|
||||
# 用 AI 整理内容
|
||||
if content and self.ai:
|
||||
content = self.ai.clean_resume(content)
|
||||
|
||||
return {
|
||||
"boss_resume_id": None, # Boss直聘 前端通常不暴露,后续可从 URL 提取
|
||||
"title": title,
|
||||
"position": position or None,
|
||||
"content": content or None,
|
||||
}
|
||||
|
||||
def _extract_detail_content(self, card) -> str | None:
|
||||
"""尝试点击简历卡片进入详情页抓取完整内容"""
|
||||
page = self.manager.page
|
||||
try:
|
||||
clickable = card.query_selector("a") or card
|
||||
clickable.click()
|
||||
page.wait_for_timeout(2000)
|
||||
detail_selectors = [
|
||||
".resume-detail",
|
||||
".geek-resume-detail",
|
||||
"[class*='resume-content']",
|
||||
".resume-preview",
|
||||
]
|
||||
for sel in detail_selectors:
|
||||
el = page.query_selector(sel)
|
||||
if el:
|
||||
content = el.inner_text().strip()
|
||||
page.go_back()
|
||||
page.wait_for_timeout(1500)
|
||||
return content
|
||||
page.go_back()
|
||||
page.wait_for_timeout(1500)
|
||||
except Exception as e:
|
||||
logger.debug(f"提取简历详情失败:{e}")
|
||||
return None
|
||||
|
||||
def _scrape_whole_page(self, page) -> list[dict]:
|
||||
"""兜底方案:抓取整个简历页主体文本作为一份简历"""
|
||||
body_selectors = [".main-wrap", ".geek-wrap", "main", "#main"]
|
||||
for sel in body_selectors:
|
||||
el = page.query_selector(sel)
|
||||
if el:
|
||||
content = el.inner_text().strip()
|
||||
if content:
|
||||
content = self.ai.clean_resume(content) if self.ai else content
|
||||
return [{
|
||||
"boss_resume_id": None,
|
||||
"title": "我的在线简历",
|
||||
"position": None,
|
||||
"content": content,
|
||||
}]
|
||||
return []
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
客户端配置
|
||||
"""
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class ClientSettings(BaseSettings):
|
||||
# -------------------------------------------------------
|
||||
# 云端服务端地址
|
||||
# -------------------------------------------------------
|
||||
SERVER_URL: str = "http://127.0.0.1:8000"
|
||||
|
||||
# -------------------------------------------------------
|
||||
# 本地 Web 控制面板
|
||||
# -------------------------------------------------------
|
||||
WEB_HOST: str = "127.0.0.1"
|
||||
WEB_PORT: int = 8088
|
||||
|
||||
# -------------------------------------------------------
|
||||
# AdsPower 本地 API
|
||||
# -------------------------------------------------------
|
||||
ADSPOWER_API_URL: str = "http://local.adspower.net:50325"
|
||||
# 要使用的 AdsPower Profile ID(在 config.env 或面板中配置)
|
||||
ADSPOWER_USER_ID: str = ""
|
||||
|
||||
# -------------------------------------------------------
|
||||
# AI 大模型(OpenAI 兼容接口)
|
||||
# -------------------------------------------------------
|
||||
AI_BASE_URL: str = "https://api.deepseek.com"
|
||||
AI_MODEL: str = "deepseek-chat"
|
||||
AI_API_KEY: str = "" # 建议通过环境变量 AI_API_KEY 注入
|
||||
AI_MIN_SCORE: int = 65
|
||||
|
||||
# -------------------------------------------------------
|
||||
# Token 持久化路径
|
||||
# -------------------------------------------------------
|
||||
TOKEN_FILE: str = "client/.token"
|
||||
|
||||
class Config:
|
||||
env_file = "client/.env"
|
||||
env_file_encoding = "utf-8"
|
||||
|
||||
|
||||
client_settings = ClientSettings()
|
||||
@@ -0,0 +1,72 @@
|
||||
"""
|
||||
机器硬件指纹生成
|
||||
通过 MAC 地址 + 磁盘序列号 + CPU ID 生成稳定的唯一编码,
|
||||
使用 SHA256 哈希,保证同一台机器每次生成结果一致。
|
||||
"""
|
||||
import hashlib
|
||||
import platform
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
|
||||
def _run_wmic(args: list[str]) -> str:
|
||||
"""执行 wmic 命令并返回输出(仅 Windows)"""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["wmic"] + args,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
encoding="utf-8",
|
||||
errors="ignore",
|
||||
)
|
||||
return result.stdout.strip()
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def get_mac_address() -> str:
|
||||
"""获取网卡 MAC 地址"""
|
||||
mac = uuid.getnode()
|
||||
return ":".join(
|
||||
"%02x" % ((mac >> (8 * i)) & 0xFF) for i in range(5, -1, -1)
|
||||
)
|
||||
|
||||
|
||||
def get_disk_serial() -> str:
|
||||
"""获取主磁盘序列号(Windows)"""
|
||||
output = _run_wmic(["diskdrive", "get", "serialnumber"])
|
||||
lines = [l.strip() for l in output.splitlines() if l.strip() and l.strip().lower() != "serialnumber"]
|
||||
return lines[0] if lines else ""
|
||||
|
||||
|
||||
def get_cpu_id() -> str:
|
||||
"""获取 CPU ProcessorId(Windows)"""
|
||||
output = _run_wmic(["cpu", "get", "processorid"])
|
||||
lines = [l.strip() for l in output.splitlines() if l.strip() and l.strip().lower() != "processorid"]
|
||||
return lines[0] if lines else ""
|
||||
|
||||
|
||||
def generate_client_code() -> str:
|
||||
"""
|
||||
生成机器唯一编码。
|
||||
组合多个硬件特征,避免单一特征缺失导致不稳定。
|
||||
"""
|
||||
parts = [
|
||||
get_mac_address(),
|
||||
get_disk_serial(),
|
||||
get_cpu_id(),
|
||||
platform.node(), # 计算机名作为兜底
|
||||
]
|
||||
raw = "|".join(parts)
|
||||
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def get_machine_summary() -> dict:
|
||||
"""返回机器基本信息(用于展示)"""
|
||||
return {
|
||||
"hostname": platform.node(),
|
||||
"system": f"{platform.system()} {platform.release()}",
|
||||
"mac": get_mac_address(),
|
||||
"client_code": generate_client_code(),
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
客户端主入口
|
||||
启动本地 Web 控制面板,并在浏览器中自动打开。
|
||||
运行方式:python -m client.main
|
||||
"""
|
||||
import sys
|
||||
import threading
|
||||
import webbrowser
|
||||
import uvicorn
|
||||
from loguru import logger
|
||||
|
||||
from .config import client_settings
|
||||
from .fingerprint import get_machine_summary
|
||||
|
||||
|
||||
def setup_logger() -> None:
|
||||
logger.remove()
|
||||
logger.add(
|
||||
sys.stderr,
|
||||
level="INFO",
|
||||
format="<green>{time:HH:mm:ss}</green> | <level>{level:<7}</level> | {message}",
|
||||
colorize=True,
|
||||
)
|
||||
logger.add(
|
||||
"client/logs/client.log",
|
||||
level="DEBUG",
|
||||
format="{time:YYYY-MM-DD HH:mm:ss} | {level:<7} | {message}",
|
||||
encoding="utf-8",
|
||||
rotation="10 MB",
|
||||
retention="7 days",
|
||||
enqueue=True,
|
||||
)
|
||||
|
||||
|
||||
def open_browser_later(url: str, delay: float = 1.5) -> None:
|
||||
def _open():
|
||||
import time
|
||||
time.sleep(delay)
|
||||
webbrowser.open(url)
|
||||
threading.Thread(target=_open, daemon=True).start()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logger()
|
||||
|
||||
machine = get_machine_summary()
|
||||
logger.info(f"本机:{machine['hostname']} ({machine['system']})")
|
||||
logger.info(f"机器指纹:{machine['client_code']}")
|
||||
logger.info(f"云端服务端地址:{client_settings.SERVER_URL}")
|
||||
|
||||
if not client_settings.ADSPOWER_USER_ID:
|
||||
logger.warning("尚未配置 AdsPower Profile ID(ADSPOWER_USER_ID),请在 client/.env 中填写")
|
||||
if not client_settings.AI_API_KEY:
|
||||
logger.warning("尚未配置 AI_API_KEY,AI 评分功能将不可用")
|
||||
|
||||
host = client_settings.WEB_HOST
|
||||
port = client_settings.WEB_PORT
|
||||
url = f"http://{host}:{port}"
|
||||
|
||||
logger.success(f"控制面板地址:{url}")
|
||||
open_browser_later(url)
|
||||
|
||||
# 启动本地 Web 服务
|
||||
uvicorn.run(
|
||||
"client.web.app:app",
|
||||
host=host,
|
||||
port=port,
|
||||
log_level="warning",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,10 @@
|
||||
# 客户端依赖
|
||||
fastapi>=0.111.0
|
||||
uvicorn[standard]>=0.30.0
|
||||
jinja2>=3.1.0
|
||||
requests>=2.31.0
|
||||
playwright>=1.44.0
|
||||
openai>=1.30.0
|
||||
pydantic>=2.7.0
|
||||
pydantic-settings>=2.3.0
|
||||
loguru>=0.7.2
|
||||
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
客户端 → 云端服务端 API 封装
|
||||
统一管理 token 持久化与请求头
|
||||
"""
|
||||
import os
|
||||
import requests
|
||||
from loguru import logger
|
||||
|
||||
from .config import client_settings
|
||||
from .fingerprint import generate_client_code
|
||||
|
||||
|
||||
class ServerAPI:
|
||||
"""调用云端 FastAPI 服务端"""
|
||||
|
||||
def __init__(self):
|
||||
self.base_url = client_settings.SERVER_URL.rstrip("/")
|
||||
self.token: str | None = None
|
||||
self.user_id: int | None = None
|
||||
self._load_token()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Token 持久化
|
||||
# ------------------------------------------------------------------
|
||||
def _token_path(self) -> str:
|
||||
path = client_settings.TOKEN_FILE
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
return path
|
||||
|
||||
def _load_token(self) -> None:
|
||||
path = self._token_path()
|
||||
if os.path.exists(path):
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
lines = f.read().strip().splitlines()
|
||||
if lines:
|
||||
self.token = lines[0]
|
||||
self.user_id = int(lines[1]) if len(lines) > 1 else None
|
||||
logger.info("已加载本地 token")
|
||||
except Exception as e:
|
||||
logger.warning(f"读取 token 失败:{e}")
|
||||
|
||||
def _save_token(self) -> None:
|
||||
with open(self._token_path(), "w", encoding="utf-8") as f:
|
||||
f.write(f"{self.token}\n{self.user_id}")
|
||||
|
||||
def _headers(self) -> dict:
|
||||
return {"Authorization": f"Bearer {self.token}"} if self.token else {}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 认证
|
||||
# ------------------------------------------------------------------
|
||||
def register(self, nickname: str | None = None) -> dict:
|
||||
"""用机器指纹注册/登录,返回 token"""
|
||||
client_code = generate_client_code()
|
||||
resp = requests.post(
|
||||
f"{self.base_url}/api/auth/register",
|
||||
json={"client_code": client_code, "nickname": nickname},
|
||||
timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
self.token = data["token"]
|
||||
self.user_id = data["user_id"]
|
||||
self._save_token()
|
||||
logger.info(f"注册/登录成功,user_id={self.user_id},新用户={data.get('is_new')}")
|
||||
return data
|
||||
|
||||
def get_me(self) -> dict:
|
||||
resp = requests.get(f"{self.base_url}/api/auth/me", headers=self._headers(), timeout=15)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
def update_login_status(self, status: str, boss_account: str | None = None) -> dict:
|
||||
payload = {"login_status": status}
|
||||
if boss_account:
|
||||
payload["boss_account"] = boss_account
|
||||
resp = requests.put(
|
||||
f"{self.base_url}/api/auth/login-status",
|
||||
json=payload, headers=self._headers(), timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 简历
|
||||
# ------------------------------------------------------------------
|
||||
def upload_resumes(self, resumes: list[dict]) -> list[dict]:
|
||||
"""批量上传简历"""
|
||||
resp = requests.post(
|
||||
f"{self.base_url}/api/resumes/batch",
|
||||
json={"resumes": resumes}, headers=self._headers(), timeout=30,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
def list_resumes(self) -> list[dict]:
|
||||
resp = requests.get(f"{self.base_url}/api/resumes", headers=self._headers(), timeout=15)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
def get_primary_resume(self) -> dict | None:
|
||||
resp = requests.get(f"{self.base_url}/api/resumes/primary", headers=self._headers(), timeout=15)
|
||||
if resp.status_code == 404:
|
||||
return None
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
def set_primary_resume(self, resume_id: int) -> dict:
|
||||
resp = requests.post(
|
||||
f"{self.base_url}/api/resumes/{resume_id}/set-primary",
|
||||
headers=self._headers(), timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 投递会话
|
||||
# ------------------------------------------------------------------
|
||||
def start_session(self, keywords: str, city_code: str,
|
||||
salary_min: int | None, salary_max: int | None) -> dict:
|
||||
resp = requests.post(
|
||||
f"{self.base_url}/api/sessions/start",
|
||||
json={
|
||||
"keywords": keywords,
|
||||
"city_code": city_code,
|
||||
"salary_min": salary_min,
|
||||
"salary_max": salary_max,
|
||||
},
|
||||
headers=self._headers(), timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
def stop_session(self, session_id: int) -> dict:
|
||||
resp = requests.post(
|
||||
f"{self.base_url}/api/sessions/{session_id}/stop",
|
||||
headers=self._headers(), timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
def update_session_stats(self, session_id: int, applied_delta: int, skipped_delta: int) -> dict:
|
||||
resp = requests.post(
|
||||
f"{self.base_url}/api/sessions/{session_id}/stats",
|
||||
json={"applied_delta": applied_delta, "skipped_delta": skipped_delta},
|
||||
headers=self._headers(), timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 投递记录
|
||||
# ------------------------------------------------------------------
|
||||
def report_application(self, session_id: int | None, data: dict) -> dict:
|
||||
params = {"session_id": session_id} if session_id else {}
|
||||
resp = requests.post(
|
||||
f"{self.base_url}/api/jobs/report",
|
||||
json=data, params=params, headers=self._headers(), timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
def check_applied(self, job_id: str) -> bool:
|
||||
resp = requests.get(
|
||||
f"{self.base_url}/api/jobs/check/{job_id}",
|
||||
headers=self._headers(), timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json().get("applied", False)
|
||||
|
||||
def get_stats(self) -> dict:
|
||||
resp = requests.get(f"{self.base_url}/api/jobs/stats", headers=self._headers(), timeout=15)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
def get_history(self, limit: int = 50, apply_type: str | None = None) -> list[dict]:
|
||||
params = {"limit": limit}
|
||||
if apply_type:
|
||||
params["apply_type"] = apply_type
|
||||
resp = requests.get(
|
||||
f"{self.base_url}/api/jobs/history",
|
||||
params=params, headers=self._headers(), timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 连通性
|
||||
# ------------------------------------------------------------------
|
||||
def ping(self) -> bool:
|
||||
try:
|
||||
resp = requests.get(f"{self.base_url}/", timeout=5)
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
@@ -0,0 +1 @@
|
||||
"""Web 控制面板包"""
|
||||
@@ -0,0 +1,273 @@
|
||||
"""
|
||||
本地 Web 控制面板
|
||||
FastAPI 应用:提供操作界面 + 编排浏览器自动化流程
|
||||
"""
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from pydantic import BaseModel
|
||||
from loguru import logger
|
||||
|
||||
from ..config import client_settings
|
||||
from ..server_api import ServerAPI
|
||||
from ..ai import AIClient
|
||||
from ..fingerprint import generate_client_code, get_machine_summary
|
||||
from ..browser.manager import BrowserManager
|
||||
from ..browser.resume_scraper import ResumeScraper
|
||||
from ..browser.applicant import Applicant
|
||||
|
||||
WEB_DIR = Path(__file__).parent
|
||||
|
||||
app = FastAPI(title="Boss直聘投递控制面板")
|
||||
app.mount("/static", StaticFiles(directory=WEB_DIR / "static"), name="static")
|
||||
templates = Jinja2Templates(directory=str(WEB_DIR / "templates"))
|
||||
|
||||
|
||||
# =======================================================
|
||||
# 全局共享状态(整个客户端生命周期复用)
|
||||
# =======================================================
|
||||
class AppState:
|
||||
def __init__(self):
|
||||
self.server_api = ServerAPI()
|
||||
self.browser = BrowserManager()
|
||||
self.ai = AIClient()
|
||||
self.applicant: Applicant | None = None
|
||||
self.connected = False # 是否已注册/登录云端
|
||||
self.login_polling = False
|
||||
|
||||
def ensure_applicant(self) -> Applicant:
|
||||
if self.applicant is None:
|
||||
self.applicant = Applicant(self.browser, self.server_api, self.ai)
|
||||
return self.applicant
|
||||
|
||||
|
||||
state = AppState()
|
||||
|
||||
|
||||
# =======================================================
|
||||
# 请求模型
|
||||
# =======================================================
|
||||
class ConnectReq(BaseModel):
|
||||
nickname: str | None = None
|
||||
|
||||
|
||||
class StartApplyReq(BaseModel):
|
||||
keywords: list[str]
|
||||
city_code: str
|
||||
salary_min: int | None = None
|
||||
salary_max: int | None = None
|
||||
greeting: str = ""
|
||||
min_score: int = 65
|
||||
delay_min: int = 3
|
||||
delay_max: int = 8
|
||||
|
||||
|
||||
# =======================================================
|
||||
# 页面
|
||||
# =======================================================
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
def index(request: Request):
|
||||
return templates.TemplateResponse("index.html", {"request": request})
|
||||
|
||||
|
||||
# =======================================================
|
||||
# 基础状态
|
||||
# =======================================================
|
||||
@app.get("/api/status")
|
||||
def get_status():
|
||||
"""返回整体状态,供前端轮询"""
|
||||
result = {
|
||||
"client_code": generate_client_code()[:16] + "...",
|
||||
"machine": get_machine_summary(),
|
||||
"server_connected": state.connected,
|
||||
"server_reachable": state.server_api.ping(),
|
||||
"adspower_running": state.browser.is_adspower_running(),
|
||||
"ai_configured": state.ai.available(),
|
||||
"login_status": "unknown",
|
||||
"resume_count": 0,
|
||||
"has_primary": False,
|
||||
"applying": False,
|
||||
"apply_stats": None,
|
||||
}
|
||||
if state.connected:
|
||||
try:
|
||||
me = state.server_api.get_me()
|
||||
result["login_status"] = me.get("login_status", "unknown")
|
||||
result["boss_account"] = me.get("boss_account")
|
||||
resumes = state.server_api.list_resumes()
|
||||
result["resume_count"] = len(resumes)
|
||||
result["has_primary"] = any(r.get("is_primary") for r in resumes)
|
||||
except Exception as e:
|
||||
logger.debug(f"获取用户状态失败:{e}")
|
||||
if state.applicant and state.applicant.is_running:
|
||||
result["applying"] = True
|
||||
result["apply_stats"] = state.applicant.stats
|
||||
return result
|
||||
|
||||
|
||||
# =======================================================
|
||||
# Step 0: 连接云端服务端
|
||||
# =======================================================
|
||||
@app.post("/api/connect")
|
||||
def connect(req: ConnectReq):
|
||||
try:
|
||||
data = state.server_api.register(req.nickname)
|
||||
state.connected = True
|
||||
return {"ok": True, "user_id": data["user_id"], "is_new": data["is_new"]}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"连接服务端失败:{e}")
|
||||
|
||||
|
||||
# =======================================================
|
||||
# Step 1: 引导登录 Boss直聘
|
||||
# =======================================================
|
||||
@app.post("/api/start-login")
|
||||
def start_login():
|
||||
"""打开 AdsPower 浏览器并跳转到 Boss直聘,等待用户手动登录"""
|
||||
if not state.connected:
|
||||
raise HTTPException(status_code=400, detail="请先连接服务端")
|
||||
try:
|
||||
state.server_api.update_login_status("logging_in")
|
||||
page = state.browser.connect()
|
||||
page.goto("https://www.zhipin.com/", wait_until="domcontentloaded", timeout=30000)
|
||||
# 启动后台轮询检测登录
|
||||
threading.Thread(target=_poll_login, daemon=True).start()
|
||||
return {"ok": True, "msg": "浏览器已打开,请在浏览器中完成登录"}
|
||||
except Exception as e:
|
||||
state.server_api.update_login_status("not_login")
|
||||
raise HTTPException(status_code=500, detail=f"打开浏览器失败:{e}")
|
||||
|
||||
|
||||
def _poll_login():
|
||||
"""后台轮询检测登录状态,最长等待 5 分钟"""
|
||||
state.login_polling = True
|
||||
import time
|
||||
for _ in range(150): # 150 * 2s = 5 分钟
|
||||
time.sleep(2)
|
||||
try:
|
||||
if state.browser.check_boss_login():
|
||||
account = state.browser.get_boss_account_name()
|
||||
state.server_api.update_login_status("logged_in", account)
|
||||
logger.success(f"登录成功:{account}")
|
||||
break
|
||||
except Exception as e:
|
||||
logger.debug(f"登录轮询异常:{e}")
|
||||
state.login_polling = False
|
||||
|
||||
|
||||
@app.get("/api/login-status")
|
||||
def login_status():
|
||||
"""前端轮询登录状态"""
|
||||
if not state.connected:
|
||||
return {"status": "not_connected", "polling": False}
|
||||
try:
|
||||
me = state.server_api.get_me()
|
||||
return {
|
||||
"status": me.get("login_status", "not_login"),
|
||||
"boss_account": me.get("boss_account"),
|
||||
"polling": state.login_polling,
|
||||
}
|
||||
except Exception:
|
||||
return {"status": "unknown", "polling": state.login_polling}
|
||||
|
||||
|
||||
# =======================================================
|
||||
# Step 2: 抓取简历 + 选择主简历
|
||||
# =======================================================
|
||||
@app.post("/api/scrape-resumes")
|
||||
def scrape_resumes():
|
||||
"""AI 抓取账号内所有简历并上传到云端"""
|
||||
if not state.connected:
|
||||
raise HTTPException(status_code=400, detail="请先连接服务端")
|
||||
try:
|
||||
scraper = ResumeScraper(state.browser, state.ai)
|
||||
resumes = scraper.scrape_all()
|
||||
if not resumes:
|
||||
raise HTTPException(status_code=404, detail="未抓取到任何简历,请确认已登录")
|
||||
uploaded = state.server_api.upload_resumes(resumes)
|
||||
return {"ok": True, "count": len(uploaded), "resumes": uploaded}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"抓取简历失败:{e}")
|
||||
|
||||
|
||||
@app.get("/api/resumes")
|
||||
def list_resumes():
|
||||
if not state.connected:
|
||||
return []
|
||||
return state.server_api.list_resumes()
|
||||
|
||||
|
||||
@app.post("/api/resumes/{resume_id}/primary")
|
||||
def set_primary(resume_id: int):
|
||||
return state.server_api.set_primary_resume(resume_id)
|
||||
|
||||
|
||||
# =======================================================
|
||||
# Step 3 & 4: 开始 / 结束投递
|
||||
# =======================================================
|
||||
@app.post("/api/start-apply")
|
||||
def start_apply(req: StartApplyReq):
|
||||
if not state.connected:
|
||||
raise HTTPException(status_code=400, detail="请先连接服务端")
|
||||
if not state.server_api.get_primary_resume():
|
||||
raise HTTPException(status_code=400, detail="请先设置主简历")
|
||||
if not state.browser.is_adspower_running():
|
||||
raise HTTPException(status_code=400, detail="AdsPower 未运行")
|
||||
|
||||
applicant = state.ensure_applicant()
|
||||
if applicant.is_running:
|
||||
raise HTTPException(status_code=400, detail="已有投递任务在运行")
|
||||
|
||||
applicant.start(
|
||||
keywords=req.keywords,
|
||||
city_code=req.city_code,
|
||||
salary_min=req.salary_min,
|
||||
salary_max=req.salary_max,
|
||||
greeting=req.greeting,
|
||||
min_score=req.min_score,
|
||||
delay_range=(req.delay_min, req.delay_max),
|
||||
)
|
||||
return {"ok": True, "session_id": applicant.session_id}
|
||||
|
||||
|
||||
@app.post("/api/stop-apply")
|
||||
def stop_apply():
|
||||
applicant = state.ensure_applicant()
|
||||
if not applicant.is_running:
|
||||
return {"ok": False, "msg": "当前没有运行中的投递任务"}
|
||||
applicant.stop()
|
||||
return {"ok": True, "msg": "正在停止投递任务..."}
|
||||
|
||||
|
||||
@app.get("/api/apply-status")
|
||||
def apply_status():
|
||||
applicant = state.applicant
|
||||
if applicant is None:
|
||||
return {"running": False, "stats": None}
|
||||
return {
|
||||
"running": applicant.is_running,
|
||||
"stats": applicant.stats,
|
||||
"session_id": applicant.session_id,
|
||||
}
|
||||
|
||||
|
||||
# =======================================================
|
||||
# 历史与统计
|
||||
# =======================================================
|
||||
@app.get("/api/history")
|
||||
def history(limit: int = 50, apply_type: str | None = None):
|
||||
if not state.connected:
|
||||
return []
|
||||
return state.server_api.get_history(limit=limit, apply_type=apply_type)
|
||||
|
||||
|
||||
@app.get("/api/stats")
|
||||
def stats():
|
||||
if not state.connected:
|
||||
return {}
|
||||
return state.server_api.get_stats()
|
||||
@@ -0,0 +1,310 @@
|
||||
// ==========================================================
|
||||
// Boss直聘 AI 投递 - 控制面板前端逻辑
|
||||
// ==========================================================
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let currentStep = 1;
|
||||
let loginPollTimer = null;
|
||||
let applyPollTimer = null;
|
||||
|
||||
// ---------- Toast ----------
|
||||
function toast(msg, ms = 3000) {
|
||||
const t = $('toast');
|
||||
t.textContent = msg;
|
||||
t.classList.add('show');
|
||||
setTimeout(() => t.classList.remove('show'), ms);
|
||||
}
|
||||
|
||||
// ---------- 步骤切换 ----------
|
||||
function goToStep(step) {
|
||||
currentStep = step;
|
||||
document.querySelectorAll('.step').forEach(el => {
|
||||
el.classList.toggle('active', parseInt(el.dataset.step) === step);
|
||||
});
|
||||
for (let i = 1; i <= 5; i++) {
|
||||
$(`panel-${i}`).classList.toggle('hidden', i !== step);
|
||||
}
|
||||
if (step === 5) loadHistory();
|
||||
if (step === 3) loadResumes();
|
||||
}
|
||||
document.querySelectorAll('.step').forEach(el => {
|
||||
el.addEventListener('click', () => goToStep(parseInt(el.dataset.step)));
|
||||
});
|
||||
|
||||
// ---------- 通用请求 ----------
|
||||
async function api(path, options = {}) {
|
||||
const res = await fetch(path, {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
...options,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.detail || `请求失败 ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
// ---------- 徽章工具 ----------
|
||||
function badge(text, cls) {
|
||||
return `<span class="badge ${cls || ''}">${text}</span>`;
|
||||
}
|
||||
|
||||
// ---------- 初始化状态 ----------
|
||||
async function refreshStatus() {
|
||||
try {
|
||||
const s = await api('/api/status');
|
||||
$('clientCode').textContent = s.client_code;
|
||||
$('serverReachable').innerHTML = badge(
|
||||
s.server_reachable ? '可连接' : '无法连接',
|
||||
s.server_reachable ? 'ok' : 'err'
|
||||
);
|
||||
$('adspowerStatus').innerHTML = badge(
|
||||
s.adspower_running ? '运行中' : '未运行',
|
||||
s.adspower_running ? 'ok' : 'warn'
|
||||
);
|
||||
// 顶部徽章
|
||||
$('statusBadges').innerHTML =
|
||||
badge(s.server_connected ? '已连接' : '未连接', s.server_connected ? 'ok' : '') +
|
||||
badge(s.ai_configured ? 'AI已配置' : 'AI未配置', s.ai_configured ? 'ok' : 'warn');
|
||||
|
||||
if (s.server_connected) {
|
||||
updateLoginBadge(s.login_status, s.boss_account);
|
||||
}
|
||||
return s;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
function updateLoginBadge(status, account) {
|
||||
const el = $('loginStatus');
|
||||
if (status === 'logged_in') {
|
||||
el.innerHTML = badge(`已登录 ${escapeHtml(account || '')}`, 'ok');
|
||||
} else if (status === 'logging_in') {
|
||||
el.innerHTML = badge('登录中...', 'warn');
|
||||
} else {
|
||||
el.innerHTML = badge('未登录', '');
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================================
|
||||
// Step 1: 连接服务端
|
||||
// ==========================================================
|
||||
$('btnConnect').addEventListener('click', async () => {
|
||||
const btn = $('btnConnect');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const data = await api('/api/connect', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ nickname: $('nickname').value || null }),
|
||||
});
|
||||
toast(data.is_new ? '注册成功!' : '登录成功!');
|
||||
await refreshStatus();
|
||||
goToStep(2);
|
||||
} catch (e) {
|
||||
toast('连接失败:' + e.message, 5000);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
// ==========================================================
|
||||
// Step 2: 登录 Boss直聘
|
||||
// ==========================================================
|
||||
$('btnStartLogin').addEventListener('click', async () => {
|
||||
const btn = $('btnStartLogin');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await api('/api/start-login', { method: 'POST' });
|
||||
toast('浏览器已打开,请在 AdsPower 浏览器中完成登录');
|
||||
$('loginSpinner').classList.remove('hidden');
|
||||
startLoginPoll();
|
||||
} catch (e) {
|
||||
toast('打开浏览器失败:' + e.message, 5000);
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
function startLoginPoll() {
|
||||
if (loginPollTimer) clearInterval(loginPollTimer);
|
||||
loginPollTimer = setInterval(async () => {
|
||||
try {
|
||||
const r = await api('/api/login-status');
|
||||
updateLoginBadge(r.status, r.boss_account);
|
||||
if (r.status === 'logged_in') {
|
||||
clearInterval(loginPollTimer);
|
||||
$('loginSpinner').classList.add('hidden');
|
||||
$('btnStartLogin').disabled = false;
|
||||
toast('登录成功!即将进入简历步骤');
|
||||
setTimeout(() => goToStep(3), 1200);
|
||||
}
|
||||
} catch (e) { /* 忽略 */ }
|
||||
}, 2500);
|
||||
}
|
||||
|
||||
// ==========================================================
|
||||
// Step 3: 抓取简历
|
||||
// ==========================================================
|
||||
$('btnScrape').addEventListener('click', async () => {
|
||||
const btn = $('btnScrape');
|
||||
btn.disabled = true;
|
||||
btn.textContent = '正在抓取...';
|
||||
try {
|
||||
const data = await api('/api/scrape-resumes', { method: 'POST' });
|
||||
toast(`抓取到 ${data.count} 份简历`);
|
||||
loadResumes();
|
||||
} catch (e) {
|
||||
toast('抓取失败:' + e.message, 5000);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '开始抓取简历';
|
||||
}
|
||||
});
|
||||
|
||||
async function loadResumes() {
|
||||
try {
|
||||
const resumes = await api('/api/resumes');
|
||||
const list = $('resumeList');
|
||||
if (!resumes.length) {
|
||||
list.innerHTML = '<p class="hint">暂无简历,请先抓取。</p>';
|
||||
return;
|
||||
}
|
||||
list.innerHTML = resumes.map(r => `
|
||||
<div class="resume-item ${r.is_primary ? 'primary' : ''}" data-id="${r.id}">
|
||||
<div class="radio"></div>
|
||||
<div>
|
||||
<div class="r-title">${escapeHtml(r.title)}</div>
|
||||
<div class="r-pos">${escapeHtml(r.position || '未设置求职意向')}</div>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
list.querySelectorAll('.resume-item').forEach(el => {
|
||||
el.addEventListener('click', () => setPrimary(parseInt(el.dataset.id)));
|
||||
});
|
||||
} catch (e) { console.error(e); }
|
||||
}
|
||||
|
||||
async function setPrimary(id) {
|
||||
try {
|
||||
await api(`/api/resumes/${id}/primary`, { method: 'POST' });
|
||||
toast('已设为主简历');
|
||||
loadResumes();
|
||||
// 允许进入下一步
|
||||
setTimeout(() => { if (currentStep === 3) goToStep(4); }, 600);
|
||||
} catch (e) {
|
||||
toast('设置失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================================
|
||||
// Step 4: 开始 / 结束投递
|
||||
// ==========================================================
|
||||
$('btnStartApply').addEventListener('click', async () => {
|
||||
const keywords = $('keywords').value.split(',').map(k => k.trim()).filter(Boolean);
|
||||
if (!keywords.length) { toast('请填写搜索关键词'); return; }
|
||||
|
||||
const btn = $('btnStartApply');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await api('/api/start-apply', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
keywords,
|
||||
city_code: $('cityCode').value,
|
||||
salary_min: parseInt($('salaryMin').value) || null,
|
||||
salary_max: parseInt($('salaryMax').value) || null,
|
||||
greeting: $('greeting').value,
|
||||
min_score: parseInt($('minScore').value) || 65,
|
||||
}),
|
||||
});
|
||||
toast('投递任务已启动');
|
||||
toggleApplyUI(true);
|
||||
startApplyPoll();
|
||||
} catch (e) {
|
||||
toast('启动失败:' + e.message, 5000);
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
$('btnStopApply').addEventListener('click', async () => {
|
||||
try {
|
||||
const r = await api('/api/stop-apply', { method: 'POST' });
|
||||
toast(r.msg);
|
||||
} catch (e) { toast('停止失败:' + e.message); }
|
||||
});
|
||||
|
||||
function toggleApplyUI(running) {
|
||||
$('btnStartApply').classList.toggle('hidden', running);
|
||||
$('btnStopApply').classList.toggle('hidden', !running);
|
||||
$('progressBox').classList.toggle('hidden', !running);
|
||||
$('btnStartApply').disabled = false;
|
||||
}
|
||||
|
||||
function startApplyPoll() {
|
||||
if (applyPollTimer) clearInterval(applyPollTimer);
|
||||
applyPollTimer = setInterval(async () => {
|
||||
try {
|
||||
const r = await api('/api/apply-status');
|
||||
if (r.stats) {
|
||||
$('progressCurrent').textContent = r.stats.current || '';
|
||||
$('statApplied').textContent = r.stats.applied || 0;
|
||||
$('statSkipped').textContent = r.stats.skipped || 0;
|
||||
}
|
||||
if (!r.running) {
|
||||
clearInterval(applyPollTimer);
|
||||
toggleApplyUI(false);
|
||||
toast('投递任务已结束');
|
||||
}
|
||||
} catch (e) { /* 忽略 */ }
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
// ==========================================================
|
||||
// Step 5: 历史与统计
|
||||
// ==========================================================
|
||||
async function loadHistory() {
|
||||
try {
|
||||
const [stats, history] = await Promise.all([
|
||||
api('/api/stats'),
|
||||
api('/api/history?limit=50'),
|
||||
]);
|
||||
$('statsGrid').innerHTML = `
|
||||
<div class="stat-card"><div class="num">${stats.total_applied || 0}</div><div class="label">累计投递</div></div>
|
||||
<div class="stat-card"><div class="num">${stats.total_chat || 0}</div><div class="label">立即沟通</div></div>
|
||||
<div class="stat-card"><div class="num">${stats.total_deliver || 0}</div><div class="label">投递简历</div></div>
|
||||
<div class="stat-card"><div class="num">${stats.today_applied || 0}</div><div class="label">今日投递</div></div>
|
||||
`;
|
||||
$('historyBody').innerHTML = history.map(h => `
|
||||
<tr>
|
||||
<td>${escapeHtml(h.job_title || '-')}</td>
|
||||
<td>${escapeHtml(h.company || '-')}</td>
|
||||
<td>${escapeHtml(h.salary || '-')}</td>
|
||||
<td><span class="tag ${safeType(h.apply_type)}">${typeLabel(h.apply_type)}</span></td>
|
||||
<td>${h.ai_score >= 0 ? h.ai_score : '-'}</td>
|
||||
<td>${formatTime(h.applied_at)}</td>
|
||||
</tr>
|
||||
`).join('') || '<tr><td colspan="6" style="text-align:center;color:#999">暂无记录</td></tr>';
|
||||
} catch (e) { console.error(e); }
|
||||
}
|
||||
|
||||
function typeLabel(t) {
|
||||
return { chat: '沟通', deliver: '投递', skipped: '跳过' }[t] || t;
|
||||
}
|
||||
// apply_type 仅允许白名单值用作 CSS class,防止注入
|
||||
function safeType(t) {
|
||||
return ['chat', 'deliver', 'skipped'].includes(t) ? t : 'skipped';
|
||||
}
|
||||
function formatTime(s) {
|
||||
if (!s) return '-';
|
||||
return s.replace('T', ' ').substring(0, 16);
|
||||
}
|
||||
function escapeHtml(s) {
|
||||
if (!s) return '';
|
||||
return s.replace(/[&<>"']/g, c => ({
|
||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
|
||||
}[c]));
|
||||
}
|
||||
|
||||
// ---------- 启动 ----------
|
||||
refreshStatus();
|
||||
setInterval(refreshStatus, 8000);
|
||||
@@ -0,0 +1,259 @@
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
:root {
|
||||
--primary: #2f6fed;
|
||||
--primary-dark: #1e56c8;
|
||||
--success: #16a34a;
|
||||
--danger: #dc2626;
|
||||
--warning: #d97706;
|
||||
--bg: #f4f6fa;
|
||||
--card: #ffffff;
|
||||
--text: #1f2937;
|
||||
--text-light: #6b7280;
|
||||
--border: #e5e7eb;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 860px;
|
||||
margin: 0 auto;
|
||||
padding: 24px 16px 60px;
|
||||
}
|
||||
|
||||
/* ===== 顶部 ===== */
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
.header h1 { font-size: 22px; }
|
||||
.status-badges { display: flex; gap: 8px; }
|
||||
|
||||
/* ===== 步骤导航 ===== */
|
||||
.steps {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-bottom: 20px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.step {
|
||||
flex: 1;
|
||||
min-width: 100px;
|
||||
text-align: center;
|
||||
padding: 10px 8px;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
color: var(--text-light);
|
||||
transition: all .2s;
|
||||
}
|
||||
.step.active {
|
||||
background: var(--primary);
|
||||
color: #fff;
|
||||
border-color: var(--primary);
|
||||
}
|
||||
.step-num {
|
||||
display: inline-block;
|
||||
width: 20px; height: 20px;
|
||||
line-height: 20px;
|
||||
border-radius: 50%;
|
||||
background: rgba(0,0,0,.08);
|
||||
margin-right: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.step.active .step-num { background: rgba(255,255,255,.25); }
|
||||
|
||||
/* ===== 面板 ===== */
|
||||
.panel {
|
||||
background: var(--card);
|
||||
border-radius: 12px;
|
||||
padding: 28px;
|
||||
box-shadow: 0 1px 4px rgba(0,0,0,.06);
|
||||
}
|
||||
.panel h2 { font-size: 19px; margin-bottom: 8px; }
|
||||
.panel .hint { color: var(--text-light); font-size: 14px; margin-bottom: 18px; }
|
||||
.hidden { display: none !important; }
|
||||
|
||||
.info-box {
|
||||
background: var(--bg);
|
||||
border-radius: 8px;
|
||||
padding: 14px 16px;
|
||||
margin-bottom: 18px;
|
||||
font-size: 14px;
|
||||
line-height: 2;
|
||||
}
|
||||
.info-box code {
|
||||
background: #eef2ff;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* ===== 徽章 ===== */
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 3px 10px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
background: var(--border);
|
||||
color: var(--text-light);
|
||||
}
|
||||
.badge.ok { background: #dcfce7; color: var(--success); }
|
||||
.badge.warn { background: #fef3c7; color: var(--warning); }
|
||||
.badge.err { background: #fee2e2; color: var(--danger); }
|
||||
|
||||
/* ===== 表单 ===== */
|
||||
.form-group { margin-bottom: 16px; }
|
||||
.form-row { display: flex; gap: 14px; }
|
||||
.form-row .form-group { flex: 1; }
|
||||
.form-group label {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
color: var(--text-light);
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.form-group input,
|
||||
.form-group select,
|
||||
.form-group textarea {
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
}
|
||||
.form-group input:focus,
|
||||
.form-group select:focus,
|
||||
.form-group textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
/* ===== 按钮 ===== */
|
||||
.btn {
|
||||
padding: 11px 22px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 15px;
|
||||
cursor: pointer;
|
||||
transition: all .2s;
|
||||
font-weight: 600;
|
||||
}
|
||||
.btn-primary { background: var(--primary); color: #fff; }
|
||||
.btn-primary:hover { background: var(--primary-dark); }
|
||||
.btn-success { background: var(--success); color: #fff; }
|
||||
.btn-success:hover { filter: brightness(1.1); }
|
||||
.btn-danger { background: var(--danger); color: #fff; }
|
||||
.btn-danger:hover { filter: brightness(1.1); }
|
||||
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.action-buttons { display: flex; gap: 12px; margin-top: 10px; }
|
||||
|
||||
/* ===== 加载 ===== */
|
||||
.spinner {
|
||||
margin-top: 16px;
|
||||
color: var(--primary);
|
||||
font-size: 14px;
|
||||
animation: pulse 1.5s infinite;
|
||||
}
|
||||
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.5} }
|
||||
|
||||
/* ===== 简历列表 ===== */
|
||||
.resume-list { margin-top: 18px; }
|
||||
.resume-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
margin-bottom: 10px;
|
||||
cursor: pointer;
|
||||
transition: all .2s;
|
||||
}
|
||||
.resume-item:hover { border-color: var(--primary); }
|
||||
.resume-item.primary {
|
||||
border-color: var(--success);
|
||||
background: #f0fdf4;
|
||||
}
|
||||
.resume-item .radio {
|
||||
width: 18px; height: 18px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.resume-item.primary .radio {
|
||||
border-color: var(--success);
|
||||
background: var(--success);
|
||||
}
|
||||
.resume-item .r-title { font-weight: 600; }
|
||||
.resume-item .r-pos { font-size: 13px; color: var(--text-light); }
|
||||
|
||||
/* ===== 进度 ===== */
|
||||
.progress-box {
|
||||
margin-top: 18px;
|
||||
padding: 16px;
|
||||
background: var(--bg);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.progress-current { font-size: 14px; margin-bottom: 10px; color: var(--primary); }
|
||||
.progress-stats { display: flex; gap: 24px; font-size: 14px; }
|
||||
|
||||
/* ===== 统计网格 ===== */
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
|
||||
gap: 12px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.stat-card {
|
||||
background: var(--bg);
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
text-align: center;
|
||||
}
|
||||
.stat-card .num { font-size: 26px; font-weight: 700; color: var(--primary); }
|
||||
.stat-card .label { font-size: 13px; color: var(--text-light); margin-top: 4px; }
|
||||
|
||||
/* ===== 历史表格 ===== */
|
||||
.history-table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||
.history-table th, .history-table td {
|
||||
padding: 10px 8px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.history-table th { color: var(--text-light); font-weight: 600; }
|
||||
.history-table td .tag {
|
||||
padding: 2px 8px; border-radius: 10px; font-size: 12px;
|
||||
}
|
||||
.tag.chat { background: #dcfce7; color: var(--success); }
|
||||
.tag.deliver { background: #dbeafe; color: var(--primary); }
|
||||
.tag.skipped { background: #f3f4f6; color: var(--text-light); }
|
||||
|
||||
/* ===== Toast ===== */
|
||||
.toast {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%) translateY(80px);
|
||||
background: #1f2937;
|
||||
color: #fff;
|
||||
padding: 12px 22px;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
opacity: 0;
|
||||
transition: all .3s;
|
||||
z-index: 999;
|
||||
max-width: 80%;
|
||||
}
|
||||
.toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
|
||||
@@ -0,0 +1,134 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Boss直聘 AI 智能投递</title>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<!-- 顶部标题栏 -->
|
||||
<header class="header">
|
||||
<h1>🎯 Boss直聘 AI 智能投递</h1>
|
||||
<div class="status-badges" id="statusBadges"></div>
|
||||
</header>
|
||||
|
||||
<!-- 步骤导航 -->
|
||||
<nav class="steps">
|
||||
<div class="step active" data-step="1"><span class="step-num">1</span> 连接</div>
|
||||
<div class="step" data-step="2"><span class="step-num">2</span> 登录</div>
|
||||
<div class="step" data-step="3"><span class="step-num">3</span> 简历</div>
|
||||
<div class="step" data-step="4"><span class="step-num">4</span> 投递</div>
|
||||
<div class="step" data-step="5"><span class="step-num">5</span> 记录</div>
|
||||
</nav>
|
||||
|
||||
<!-- Step 1: 连接服务端 -->
|
||||
<section class="panel" id="panel-1">
|
||||
<h2>连接云端服务端</h2>
|
||||
<p class="hint">使用本机硬件指纹作为唯一编码注册,数据将隔离存储在你的账号下。</p>
|
||||
<div class="info-box">
|
||||
<div><strong>机器指纹:</strong><code id="clientCode">加载中...</code></div>
|
||||
<div><strong>服务端状态:</strong><span id="serverReachable" class="badge">检测中</span></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>昵称(可选)</label>
|
||||
<input type="text" id="nickname" placeholder="给自己起个名字">
|
||||
</div>
|
||||
<button class="btn btn-primary" id="btnConnect">连接并注册</button>
|
||||
</section>
|
||||
|
||||
<!-- Step 2: 登录 Boss直聘 -->
|
||||
<section class="panel hidden" id="panel-2">
|
||||
<h2>登录 Boss直聘</h2>
|
||||
<p class="hint">点击下方按钮,将通过 AdsPower 指纹浏览器打开 Boss直聘,请在弹出的浏览器窗口中手动完成登录(扫码或账号密码)。</p>
|
||||
<div class="info-box">
|
||||
<div><strong>AdsPower 状态:</strong><span id="adspowerStatus" class="badge">检测中</span></div>
|
||||
<div><strong>登录状态:</strong><span id="loginStatus" class="badge">未登录</span></div>
|
||||
</div>
|
||||
<button class="btn btn-primary" id="btnStartLogin">打开浏览器登录</button>
|
||||
<div class="spinner hidden" id="loginSpinner">正在等待登录,请在浏览器中完成操作...</div>
|
||||
</section>
|
||||
|
||||
<!-- Step 3: 简历管理 -->
|
||||
<section class="panel hidden" id="panel-3">
|
||||
<h2>抓取并选择主简历</h2>
|
||||
<p class="hint">AI 将自动抓取你 Boss直聘 账号内的所有简历,请勾选一份作为主简历用于 JD 匹配。</p>
|
||||
<button class="btn btn-primary" id="btnScrape">开始抓取简历</button>
|
||||
<div class="resume-list" id="resumeList"></div>
|
||||
</section>
|
||||
|
||||
<!-- Step 4: 配置投递 -->
|
||||
<section class="panel hidden" id="panel-4">
|
||||
<h2>配置并开始投递</h2>
|
||||
<div class="form-group">
|
||||
<label>搜索关键词(多个用逗号分隔)</label>
|
||||
<input type="text" id="keywords" placeholder="如:Python开发,后端工程师" value="Python开发">
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label>城市</label>
|
||||
<select id="cityCode">
|
||||
<option value="101010100">北京</option>
|
||||
<option value="101020100">上海</option>
|
||||
<option value="101280100">广州</option>
|
||||
<option value="101280600">深圳</option>
|
||||
<option value="101210100">杭州</option>
|
||||
<option value="101190100">成都</option>
|
||||
<option value="101110100">西安</option>
|
||||
<option value="101120100">济南</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>AI 最低匹配分</label>
|
||||
<input type="number" id="minScore" value="65" min="0" max="100">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label>最低薪资 (K)</label>
|
||||
<input type="number" id="salaryMin" value="15" min="0">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>最高薪资 (K)</label>
|
||||
<input type="number" id="salaryMax" value="40" min="0">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>打招呼语(留空使用默认)</label>
|
||||
<textarea id="greeting" rows="2" placeholder="您好,我对贵司岗位很感兴趣..."></textarea>
|
||||
</div>
|
||||
<div class="action-buttons">
|
||||
<button class="btn btn-success" id="btnStartApply">▶ 开始投递</button>
|
||||
<button class="btn btn-danger hidden" id="btnStopApply">■ 结束投递</button>
|
||||
</div>
|
||||
<div class="progress-box hidden" id="progressBox">
|
||||
<div class="progress-current" id="progressCurrent">准备中...</div>
|
||||
<div class="progress-stats">
|
||||
<span>已投递:<strong id="statApplied">0</strong></span>
|
||||
<span>已跳过:<strong id="statSkipped">0</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Step 5: 投递记录 -->
|
||||
<section class="panel hidden" id="panel-5">
|
||||
<h2>投递记录与统计</h2>
|
||||
<div class="stats-grid" id="statsGrid"></div>
|
||||
<table class="history-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>职位</th><th>公司</th><th>薪资</th><th>方式</th><th>AI评分</th><th>时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="historyBody"></tbody>
|
||||
</table>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- Toast 提示 -->
|
||||
<div class="toast" id="toast"></div>
|
||||
|
||||
<script src="/static/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user