import urllib.parse, time
from playwright.sync_api import sync_playwright
URL='http://127.0.0.1:8848/'+urllib.parse.quote('组卷台.html')
with sync_playwright() as p:
    b=p.chromium.launch(headless=True); pg=b.new_page(viewport={'width':1440,'height':950})
    errs=[]; pg.on('pageerror',lambda e:errs.append(str(e)[:150]))
    pg.goto(URL,timeout=600000,wait_until='domcontentloaded'); pg.wait_for_selector('#bCompose',timeout=600000); time.sleep(2)
    for tb,gg in [('上海中考真题','2024年'),('上海校本卷',None),('全国中考真题','云南')]:
        pg.select_option('#ftb',tb); time.sleep(0.3)
        if gg is None: gg=pg.evaluate("document.querySelectorAll('#fg option')[1].value")
        pg.select_option('#fg',gg); time.sleep(0.4)
        sec=pg.evaluate("[...document.querySelectorAll('#fsec option')].map(o=>o.value).filter(Boolean)[0]")
        pg.select_option('#fsec',sec); time.sleep(3)
        bar=pg.evaluate("(()=>{const e=document.querySelector('#srcbar')||document.querySelector('[id*=src]');return e?e.innerText.slice(0,300):'(no bar)'})()")
        links=pg.evaluate("[...document.querySelectorAll('a[href*=\"/api/paper\"]')].map(a=>a.textContent.trim()+' -> '+a.getAttribute('href'))")
        print('==',tb,gg,sec); print('  ',bar.replace('\n',' | ')); [print('  ',l) for l in links[:8]]
        pv=[l for l in links if 'preview' in l]
        if pv:
            href=pv[0].split('-> ')[1]; r=pg.request.get('http://127.0.0.1:8848'+href); t=r.text()
            print('   preview HTTP',r.status,'页图数',t.count('/api/page?'))
    print('JS errors:',errs)
    b.close()
