diff --git a/server/recruit.py b/server/recruit.py index 2330015..6a70b63 100644 --- a/server/recruit.py +++ b/server/recruit.py @@ -26,6 +26,7 @@ from .models import recruit_announcements SOURCE = "https://school.gxjy.sdei.edu.cn" LIST_ENDPOINT = SOURCE + "/sdmu/front/indexZpggList" DETAIL_ENDPOINT = SOURCE + "/sdmu/jiuye/zhaopingg/detail" +DETAIL_HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36"} logger = logging.getLogger(__name__) MAX_IMAGE_EDGE = 1800 @@ -69,6 +70,24 @@ def html_to_text(content: str) -> str: return parser.text() +def extract_detail_html(content: str) -> str: + """提取详情页服务端渲染的正文和职位列表。""" + positions_match = re.search( + r']+class="(?:[^"]*\s)?selected-positions(?:\s[^"]*)?"', + content, + flags=re.I, + ) + if not positions_match: + return "" + start = positions_match.start() + depth = 0 + for match in re.finditer(r']*>|', content[start:], flags=re.I): + depth += 1 if match.group(0).startswith(" str: src = (src or "").strip() if not src or src.startswith(("data:", "file:")): @@ -231,6 +250,23 @@ async def fetch_page(client: httpx.AsyncClient, page: int, page_size: int = 50): raise RuntimeError("就业平台暂时无法访问") from last_error +async def fetch_detail_html(client: httpx.AsyncClient, gonggao_id: int) -> str: + last_error: Exception | None = None + for attempt in range(2): + try: + response = await asyncio.wait_for( + client.get(f"{DETAIL_ENDPOINT}/{gonggao_id}", headers=DETAIL_HEADERS), + timeout=15, + ) + response.raise_for_status() + return response.text + except (httpx.HTTPError, asyncio.TimeoutError) as exc: + last_error = exc + if attempt == 0: + await asyncio.sleep(0.4) + raise RuntimeError(f"公告详情页获取失败({gonggao_id})") from last_error + + async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict: owns_client = client is None if owns_client: @@ -238,11 +274,23 @@ async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict: added = updated = 0 try: first = await fetch_page(client, 1) - pages = int(first.get("extra", {}).get("pages") or 1) + pages = max(1, int(first.get("extra", {}).get("pages") or 1)) + page_size = 50 + pages = max(pages, -(-len(first.get("rows") or []) // page_size)) rows = list(first.get("rows") or []) for page in range(2, pages + 1): await asyncio.sleep(0.15) rows.extend((await fetch_page(client, page)).get("rows") or []) + details: dict[int, str] = {} + for raw in rows: + content = str(raw.get("gonggaoContent") or "").strip() + if len(content) <= 20 and not raw.get("iswailian"): + try: + gonggao_id = int(raw["gonggaoId"]) + await asyncio.sleep(0.15) + details[gonggao_id] = await fetch_detail_html(client, gonggao_id) + except (KeyError, TypeError, ValueError, RuntimeError): + logger.warning("公告详情补抓失败:%s", raw.get("gonggaoId"), exc_info=True) finally: if owns_client: await client.aclose() @@ -256,7 +304,7 @@ async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict: "gonggao_id": gonggao_id, "title": str(raw.get("gonggaoTitle") or "未命名公告"), "companyname": str(raw.get("companyname") or ""), - "content_html": str(raw.get("gonggaoContent") or ""), + "content_html": details.get(gonggao_id) and extract_detail_html(details[gonggao_id]) or str(raw.get("gonggaoContent") or ""), "create_time": str(raw.get("createTime") or ""), "check_time": str(raw.get("checkTime") or ""), "valid_time": str(raw.get("validTime") or ""), diff --git a/tests/test_recruit.py b/tests/test_recruit.py index 0105ec3..e4e8acc 100644 --- a/tests/test_recruit.py +++ b/tests/test_recruit.py @@ -38,6 +38,8 @@ class RecruitTests(ApiTestCase): with patch.object(recruit, 'fetch_page', new=fetch): data = (await self.client.post('/api/recruit/sync', headers=auth(owner['token']))).json() self.assertEqual(data, {'fetched': 1, 'added': 1, 'updated': 0}) + detail = await self.client.get('/api/recruit/announcements/1', headers=auth(owner['token'])) + self.assertEqual(detail.json()['content_html'], '

第一段

第二段
') rows = (await self.client.get('/api/recruit/announcements', headers=auth(owner['token']))).json() self.assertEqual(rows['total'], 1) self.assertEqual(rows['items'][0]['gonggao_id'], 1) @@ -56,3 +58,21 @@ class RecruitTests(ApiTestCase): self.assertIn('原文链接', response.text) response = await self.client.get('/api/recruit/export', headers=auth(owner['token'])) self.assertEqual(response.status_code, 422) + + async def test_sync_fetches_detail_for_empty_content(self): + owner = await register(self.client, 'recruit-detail') + raw = dict(RAW, gonggaoId=2, gonggaoContent='


') + fetch = AsyncMock(return_value={"code": 0, "rows": [raw], "extra": {"pages": 1}}) + fetch_detail = AsyncMock(return_value=''' +


+
+ 职位列表 +
外贸业务员
+
+ ''') + with patch.object(recruit, 'fetch_page', new=fetch), patch.object(recruit, 'fetch_detail_html', new=fetch_detail): + data = (await self.client.post('/api/recruit/sync', headers=auth(owner['token']))).json() + self.assertEqual(data, {'fetched': 1, 'added': 1, 'updated': 0}) + fetch_detail.assert_awaited_once() + detail = (await self.client.get('/api/recruit/announcements/2', headers=auth(owner['token']))).json() + self.assertIn('外贸业务员', detail['content_html'])