如何通过Selenium的execute_javascript获取DevTools网络数据验证Canvas请求
execute_script Got it, let's walk through how to intercept the network request triggered by your Canvas save action, extract its payload/response, and validate the Canvas operations directly—no OCR needed:
1. Inject a Network Request Listener via execute_script
First, we'll inject JavaScript into the page to intercept fetch requests (most modern apps use this; we can adjust for XMLHttpRequest if needed). This listener will capture requests matching your save endpoint and store their details for later validation.
Run this before clicking the save button:
# Initialize empty objects to hold captured data driver.execute_script(""" // Store captured request/response in the window object for Selenium to access window.capturedRequest = {}; window.capturedResponse = {}; // Override the native fetch function to intercept requests const originalFetch = window.fetch; window.fetch = async (...args) => { const [url, options] = args; // Match your save endpoint (adjust the URL pattern to your actual endpoint) if (url.includes('/canvas/save')) { // Capture core request details window.capturedRequest.url = url; window.capturedRequest.method = options?.method || 'GET'; window.capturedRequest.payload = options?.body ? await options.text() : null; } // Proceed with the original fetch call const response = await originalFetch(...args); // Clone the response to read its body without consuming it const clonedResponse = response.clone(); if (url.includes('/canvas/save')) { window.capturedResponse.status = response.status; window.capturedResponse.body = await clonedResponse.text(); } return response; }; """)
2. Perform Canvas Actions & Trigger Save
Execute your Canvas drawing operations (like drawing lines/shapes) and click the save button using Selenium:
from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By import time # Example: Simulate drawing on the Canvas (adjust to your actual interaction code) canvas = driver.find_element(By.TAG_NAME, 'canvas') action_chains = ActionChains(driver) action_chains.move_to_element(canvas).click_and_hold().move_by_offset(75, 75).release().perform() # Click the save button to trigger the network request save_button = driver.find_element(By.ID, 'save-canvas-btn') save_button.click() # Wait briefly for the request/response to complete (use WebDriverWait for better reliability) time.sleep(1)
3. Extract & Validate Captured Data
Now retrieve the captured request and response, then validate the payload (which should contain your Canvas operation details):
# Fetch captured data from the window object request_data = driver.execute_script("return window.capturedRequest;") response_data = driver.execute_script("return window.capturedResponse;") # Log and validate the data print("Captured Request Payload:", request_data['payload']) print("Response Status Code:", response_data['status']) print("Response Body:", response_data['body']) # Example validation checks assert request_data['method'] == 'POST', "Save request should use POST method" assert 'shapeType: "line"' in request_data['payload'], "Canvas line operation not found in request payload" assert response_data['status'] == 200, "Save request failed with non-200 status code"
Key Tips for Reliability:
- Adjust the URL Match: Modify
url.includes('/canvas/save')to match your actual save endpoint's URL pattern. - XMLHttpRequest Support: If your app uses
XMLHttpRequestinstead offetch, replace the fetch override with a listener forXMLHttpRequest'ssendmethod andloadevent. - Replace Sleep with WebDriverWait: For more robust waits, use
WebDriverWaitto wait untilwindow.capturedRequest.payloadis not null instead oftime.sleep(). - Parse JSON Payloads: If the payload is JSON, parse it in the injected JS or in Python with
json.loads(request_data['payload'])for easier property-based validation.
This approach lets you directly access the exact data sent from the Canvas to the server, so you can validate every detail of your drawing operations without relying on image-based tools.
内容的提问来源于stack exchange,提问作者Ravi Nagar

