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

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

# 查找标题区域
cmd = json.dumps({'id': 1, 'method': 'Runtime.evaluate', 'params': {
    'expression': '''
    (function() {
        // 查找包含"标题"文字的元素
        var allElements = document.querySelectorAll('*');
        for (var i = 0; i < allElements.length; i++) {
            if (allElements[i].textContent && allElements[i].textContent.trim() === '标题') {
                return 'Found title label, parent: ' + allElements[i].parentElement.tagName + ', next sibling: ' + (allElements[i].nextElementSibling ? allElements[i].nextElementSibling.tagName : 'none');
            }
        }
        return 'Title label not found';
    })()
    '''}})
ws.send(cmd)
time.sleep(0.5)
result = ws.recv()
data = json.loads(result)
print('=== 标题区域 ===')
print(data.get('result', {}).get('result', {}).get('value', 'NO_DATA'))

# 查找所有textarea
cmd2 = json.dumps({'id': 2, 'method': 'Runtime.evaluate', 'params': {
    'expression': '''
    (function() {
        var textareas = document.querySelectorAll('textarea');
        var result = [];
        for (var i = 0; i < textareas.length; i++) {
            result.push(i + ': ' + textareas[i].id + ' / ' + textareas[i].name + ' / ' + textareas[i].placeholder);
        }
        return result.join('\\n') || 'No textareas';
    })()
    '''}})
ws.send(cmd2)
time.sleep(0.5)
result2 = ws.recv()
data2 = json.loads(result2)
print('=== 所有textarea ===')
print(data2.get('result', {}).get('result', {}).get('value', 'NO_DATA'))

ws.close()
