修复招聘公告空正文与漏同步
This commit is contained in:
+50
-2
@@ -26,6 +26,7 @@ from .models import recruit_announcements
|
|||||||
SOURCE = "https://school.gxjy.sdei.edu.cn"
|
SOURCE = "https://school.gxjy.sdei.edu.cn"
|
||||||
LIST_ENDPOINT = SOURCE + "/sdmu/front/indexZpggList"
|
LIST_ENDPOINT = SOURCE + "/sdmu/front/indexZpggList"
|
||||||
DETAIL_ENDPOINT = SOURCE + "/sdmu/jiuye/zhaopingg/detail"
|
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__)
|
logger = logging.getLogger(__name__)
|
||||||
MAX_IMAGE_EDGE = 1800
|
MAX_IMAGE_EDGE = 1800
|
||||||
|
|
||||||
@@ -69,6 +70,24 @@ def html_to_text(content: str) -> str:
|
|||||||
return parser.text()
|
return parser.text()
|
||||||
|
|
||||||
|
|
||||||
|
def extract_detail_html(content: str) -> str:
|
||||||
|
"""提取详情页服务端渲染的正文和职位列表。"""
|
||||||
|
positions_match = re.search(
|
||||||
|
r'<div[^>]+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'<div\b[^>]*>|</div\s*>', content[start:], flags=re.I):
|
||||||
|
depth += 1 if match.group(0).startswith("<div") else -1
|
||||||
|
if depth == 0:
|
||||||
|
return content[start:start + match.end()].strip()
|
||||||
|
return content[start:].strip()
|
||||||
|
|
||||||
|
|
||||||
def image_url(src: str) -> str:
|
def image_url(src: str) -> str:
|
||||||
src = (src or "").strip()
|
src = (src or "").strip()
|
||||||
if not src or src.startswith(("data:", "file:")):
|
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
|
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:
|
async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict:
|
||||||
owns_client = client is None
|
owns_client = client is None
|
||||||
if owns_client:
|
if owns_client:
|
||||||
@@ -238,11 +274,23 @@ async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict:
|
|||||||
added = updated = 0
|
added = updated = 0
|
||||||
try:
|
try:
|
||||||
first = await fetch_page(client, 1)
|
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 [])
|
rows = list(first.get("rows") or [])
|
||||||
for page in range(2, pages + 1):
|
for page in range(2, pages + 1):
|
||||||
await asyncio.sleep(0.15)
|
await asyncio.sleep(0.15)
|
||||||
rows.extend((await fetch_page(client, page)).get("rows") or [])
|
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:
|
finally:
|
||||||
if owns_client:
|
if owns_client:
|
||||||
await client.aclose()
|
await client.aclose()
|
||||||
@@ -256,7 +304,7 @@ async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict:
|
|||||||
"gonggao_id": gonggao_id,
|
"gonggao_id": gonggao_id,
|
||||||
"title": str(raw.get("gonggaoTitle") or "未命名公告"),
|
"title": str(raw.get("gonggaoTitle") or "未命名公告"),
|
||||||
"companyname": str(raw.get("companyname") 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 ""),
|
"create_time": str(raw.get("createTime") or ""),
|
||||||
"check_time": str(raw.get("checkTime") or ""),
|
"check_time": str(raw.get("checkTime") or ""),
|
||||||
"valid_time": str(raw.get("validTime") or ""),
|
"valid_time": str(raw.get("validTime") or ""),
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ class RecruitTests(ApiTestCase):
|
|||||||
with patch.object(recruit, 'fetch_page', new=fetch):
|
with patch.object(recruit, 'fetch_page', new=fetch):
|
||||||
data = (await self.client.post('/api/recruit/sync', headers=auth(owner['token']))).json()
|
data = (await self.client.post('/api/recruit/sync', headers=auth(owner['token']))).json()
|
||||||
self.assertEqual(data, {'fetched': 1, 'added': 1, 'updated': 0})
|
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'], '<p>第一段</p><img src="https://example.com/a.png"><div>第二段</div>')
|
||||||
rows = (await self.client.get('/api/recruit/announcements', headers=auth(owner['token']))).json()
|
rows = (await self.client.get('/api/recruit/announcements', headers=auth(owner['token']))).json()
|
||||||
self.assertEqual(rows['total'], 1)
|
self.assertEqual(rows['total'], 1)
|
||||||
self.assertEqual(rows['items'][0]['gonggao_id'], 1)
|
self.assertEqual(rows['items'][0]['gonggao_id'], 1)
|
||||||
@@ -56,3 +58,21 @@ class RecruitTests(ApiTestCase):
|
|||||||
self.assertIn('原文链接', response.text)
|
self.assertIn('原文链接', response.text)
|
||||||
response = await self.client.get('/api/recruit/export', headers=auth(owner['token']))
|
response = await self.client.get('/api/recruit/export', headers=auth(owner['token']))
|
||||||
self.assertEqual(response.status_code, 422)
|
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='<p><br></p>')
|
||||||
|
fetch = AsyncMock(return_value={"code": 0, "rows": [raw], "extra": {"pages": 1}})
|
||||||
|
fetch_detail = AsyncMock(return_value='''
|
||||||
|
<div class="txt"><p><br></p></div>
|
||||||
|
<div class="selected-positions">
|
||||||
|
<span>职位列表</span>
|
||||||
|
<table><tr><td>外贸业务员</td></tr></table>
|
||||||
|
</div>
|
||||||
|
''')
|
||||||
|
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'])
|
||||||
|
|||||||
Reference in New Issue
Block a user