#!/usr/bin/env python3
"""探测 gddrc: 定位正文精确容器"""
import asyncio, re, sys

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"

async def main():
    from playwright.async_api import async_playwright
    from playwright_stealth import Stealth
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            executable_path='/root/.cache/ms-playwright/chromium-1228/chrome-linux64/chrome',
            args=['--no-sandbox', '--disable-setuid-sandbox', '--disable-blink-features=AutomationControlled']
        )
        stealth = Stealth()
        ctx = await browser.new_context(user_agent=UA, locale='zh-CN',
                                        viewport={'width': 1440, 'height': 900}, timezone_id='Asia/Shanghai')
        await stealth.apply_stealth_async(ctx)
        page = await ctx.new_page()

        for attempt in range(3):
            try:
                await page.goto("https://drc.gd.gov.cn/gdsnyj/gkmlpt/index#3869", wait_until='domcontentloaded', timeout=60000)
                await page.wait_for_timeout(8000)
                break
            except Exception:
                await page.wait_for_timeout(20000)

        url = "http://drc.gd.gov.cn/gdsnyj/gkmlpt/content/4/4939/post_4939705.html"
        await page.goto(url, wait_until='domcontentloaded', timeout=45000)
        await page.wait_for_timeout(5000)

        # 找含"粤能许可"且最短的 div (正文容器)
        info = await page.evaluate("""() => {
            const results = [];
            document.querySelectorAll('div').forEach(d => {
                const t = (d.innerText||'');
                if (t.includes('粤能许可') && t.length > 300) {
                    results.push({cls: d.className.slice(0,70), id: d.id, len: t.length, tag: d.tagName});
                }
            });
            // 按长度升序 (最短的 = 最精确容器)
            results.sort((a,b) => a.len - b.len);
            return results.slice(0,8);
        }""")
        for r in info:
            print(f"  div.{r['cls']} id={r['id']} len={r['len']}")

        # 用最短容器提取正文
        if info:
            shortest = info[0]['cls']
            content = await page.evaluate(f"""() => {{
                const els = [...document.querySelectorAll('div.{shortest.split(' ')[0]}')].filter(d => (d.innerText||'').includes('粤能许可') && (d.innerText||'').length > 300);
                if (els.length) return {{cls: els[0].className, html: els[0].outerHTML.slice(0, 800)}};
                return null;
            }}""")
            if content:
                print(f"\n正文容器: {content['cls']}")
                print(content['html'][:600])

        await browser.close()

asyncio.run(main())
