# -*- coding: utf-8 -*-
import sys
sys.stdout.reconfigure(encoding='utf-8')
import websocket, json, time

ws_url = 'ws://localhost:9222/devtools/page/6E98C43D3729FCDFDDC3947B93A7190C'
ws = websocket.create_connection(ws_url)
ws.settimeout(10)

# 获取实际正文内容长度
cmd = json.dumps({'id': 1, 'method': 'Runtime.evaluate', 'params': {
    'expression': 'document.body.innerText.length'}})
ws.send(cmd)
time.sleep(0.3)
result = ws.recv()
data = json.loads(result)
body_len = data.get('result', {}).get('result', {}).get('value', 0)
print('页面总文本长度:', body_len)

# 获取正文前200字
cmd2 = json.dumps({'id': 2, 'method': 'Runtime.evaluate', 'params': {
    'expression': 'document.body.innerText.substring(0, 200)'}})
ws.send(cmd2)
time.sleep(0.3)
result2 = ws.recv()
data2 = json.loads(result2)
text = data2.get('result', {}).get('result', {}).get('value', '')
print('\\n正文预览:')
print(text[:200])

ws.close()
