#!/usr/bin/env python3
"""探测 ahtxq: 点击下一页看请求"""
import asyncio, json, 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, viewport={'width':1366,'height':900})
        await stealth.apply_stealth_async(ctx)
        page = await ctx.new_page()

        print("="*60)
        print("[ahtxq] tzgg 点击翻页抓请求")
        reqs = []
        page.on('request', lambda req: reqs.append((req.method, req.url)) if any(k in req.url for k in ['label', '8888', 'list', 'json', 'Ajax', 'page', 'Page']) else None)
        await page.goto("https://www.ahtxq.gov.cn/zxzx/tzgg/index.html", timeout=30000, wait_until='domcontentloaded')
        await page.wait_for_timeout(3500)
        # 点击下一页 (最后一个 pager a)
        clicked = await page.evaluate("""() => {
            const as = [...document.querySelectorAll('a')];
            const next = as.filter(a => (a.innerText||'').trim() === '下一页' || (a.innerText||'').trim() === '2');
            if (next[0]) { next[0].click(); return true; }
            return false;
        }""")
        print(f"  clicked: {clicked}")
        await page.wait_for_timeout(3000)
        print(f"  请求 ({len(reqs)}):")
        for m, u in reqs[-15:]:
            print(f"    {m} {u[:160]}")
        # 第2页内容
        items = await page.evaluate("""() => {
            const out = [];
            document.querySelectorAll('li a[href*=".html"]').forEach(a => {
                const t = (a.innerText||'').trim();
                if (t && t.length>8 && /\\d{6,}\\.html/.test(a.href)) out.push({t: t.slice(0,40), h: a.href});
            });
            return out.slice(0,8);
        }""")
        print(f"  当前列表 ({len(items)}):")
        for it in items:
            print(f"    [{it['t']}] {it['h'][:80]}")

        await browser.close()

asyncio.run(main())
