Okay, here's a Python Selenium script using Selenium 4+ and the Chrome DevTools Protocol (CDP) to click a button, intercept the subsequent AJAX request's response, and print its content.
Why Selenium 4+ and CDP?
- Selenium itself doesn't have a built-in, high-level API specifically for intercepting network responses like dedicated tools (e.g., Puppeteer, Playwright) or proxy-based solutions might.
- However, Selenium 4+ provides direct access to the browser's Chrome DevTools Protocol (CDP). This allows us to interact with the browser at a much lower level, including enabling network event listeners.
Prerequisites:
- Python: Installed.
- Selenium: Installed (
pip install selenium).
- WebDriver: You need the appropriate WebDriver for your browser (e.g., ChromeDriver for Chrome, GeckoDriver for Firefox) installed and ideally in your system's PATH or specified explicitly. This example uses Chrome.
- Selenium 4: This script relies on features introduced or significantly improved in Selenium 4.
The Code:
import json
import time
import base64 # For handling potential base64 encoded responses
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
# --- Configuration: YOU MUST CHANGE THESE ---
TARGET_URL = "https://www.example.com" # Replace with the actual URL of the page
# Selector for the button that triggers the AJAX request
# Examples: (By.ID, "submitButton"), (By.CSS_SELECTOR, ".btn.ajax-trigger"), (By.XPATH, "//button[contains(text(), 'Load Data')]")
BUTTON_SELECTOR = (By.ID, "yourButtonId")
# A unique part of the URL of the AJAX response you want to catch.
# This helps filter out other network requests.
# Examples: "/api/data", "get_user_info", "status.json"
AJAX_RESPONSE_URL_PATTERN = "/api/data"
# --- End Configuration ---
# --- Global variable to store response details ---
# We use a dictionary to hold details, making it easier to pass info from the listener
ajax_response_details = {
"requestId": None,
"url": None,
"status": None,
"response_body": None,
"error": None
}
def handle_network_response(response_data):
"""Callback function to handle Network.responseReceived events."""
global ajax_response_details
# Only process if we haven't found our target response yet
if ajax_response_details["requestId"] is None and response_data.get("response"):
response = response_data["response"]
request_id = response_data.get("requestId")
url = response.get("url")
status = response.get("status")
# Check if this response matches our target pattern
# Be specific enough to avoid catching unrelated requests
if AJAX_RESPONSE_URL_PATTERN in url:
print(f"\n[*] Found potential target response:")
print(f" Request ID: {request_id}")
print(f" URL: {url}")
print(f" Status: {status}")
ajax_response_details["requestId"] = request_id
ajax_response_details["url"] = url
ajax_response_details["status"] = status
# We've identified the request, but we fetch the body later
# to avoid blocking the listener thread.
def get_ajax_response_body(driver, request_id):
"""Fetches the response body using CDP's Network.getResponseBody."""
try:
# Use execute_cdp_cmd to call the CDP command
response = driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": request_id})
body = response.get('body', None)
is_base64 = response.get('base64Encoded', False)
if body is None:
return None # No body content
if is_base64:
# Decode if it's base64 encoded
decoded_body = base64.b64decode(body).decode('utf-8', errors='ignore')
return decoded_body
else:
# Assuming UTF-8 encoding, adjust if needed based on response headers
# The 'body' might already be a string if not base64
return body
except Exception as e:
print(f"[!] Error getting response body for request ID '{request_id}': {e}")
ajax_response_details["error"] = f"Failed to get body: {e}"
return None
# --- Main Script Execution ---
driver = None # Initialize driver variable
try:
# --- WebDriver Setup ---
# Configure Chrome options
options = webdriver.ChromeOptions()
# options.add_argument("--headless") # Run in background without opening a browser window
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
# Add CDP command line arguments if necessary (often handled automatically)
# options.add_argument("--remote-debugging-port=9222")
# Initialize WebDriver
print("Initializing WebDriver...")
driver = webdriver.Chrome(options=options)
driver.implicitly_wait(5) # Set implicit wait for finding elements
# --- Enable Network Event Listening via CDP ---
print("Enabling Chrome DevTools Protocol (CDP) Network events...")
driver.execute_cdp_cmd("Network.enable", {})
# Add the listener *before* navigating or performing actions
driver.add_cdp_listener("Network.responseReceived", handle_network_response)
print("CDP Network listener attached.")
# --- Navigation ---
print(f"Navigating to {TARGET_URL}...")
driver.get(TARGET_URL)
print("Page loaded.")
# --- Find and Click the Button ---
print(f"Looking for button with selector: {BUTTON_SELECTOR}")
wait = WebDriverWait(driver, 15) # Increase timeout if needed
button = wait.until(EC.element_to_be_clickable(BUTTON_SELECTOR))
print("Clicking the button...")
# Sometimes JS click is more reliable if element is complex
# driver.execute_script("arguments[0].click();", button)
button.click()
print("Button clicked.")
# --- Wait for the AJAX Response ---
# Use WebDriverWait with a lambda function to check our global variable
print(f"Waiting for AJAX response matching pattern '{AJAX_RESPONSE_URL_PATTERN}'...")
try:
wait.until(lambda d: ajax_response_details["requestId"] is not None)
print("Target AJAX response detected.")
# --- Retrieve and Process Response Body ---
print("\n--- Processing Captured Response ---")
captured_request_id = ajax_response_details["requestId"]
response_body = get_ajax_response_body(driver, captured_request_id)
if response_body is not None:
ajax_response_details["response_body"] = response_body
print(f"Response Body (Request ID: {captured_request_id}):")
# Try to print as formatted JSON, otherwise print as raw text
try:
parsed_json = json.loads(response_body)
print(json.dumps(parsed_json, indent=4))
except json.JSONDecodeError:
print(response_body) # Print raw if not valid JSON
elif ajax_response_details["error"]:
print(f"Could not retrieve body: {ajax_response_details['error']}")
else:
print("Response body appears to be empty or could not be retrieved.")
except TimeoutException:
print(f"[!] Timeout: Did not detect the AJAX response matching '{AJAX_RESPONSE_URL_PATTERN}' within the time limit.")
except Exception as e:
print(f"[!] An error occurred while waiting for or retrieving the response: {e}")
except NoSuchElementException:
print(f"[!] Error: Could not find the button using selector {BUTTON_SELECTOR}.")
except TimeoutException:
print(f"[!] Error: Timed out waiting for the page or button to load.")
except Exception as e:
print(f"[!] An unexpected error occurred: {e}")
# Optional: Print stack trace for debugging
# import traceback
# traceback.print_exc()
finally:
# --- Cleanup ---
if driver:
# Optional: Disable network events if you were doing more after this
# try:
# driver.execute_cdp_cmd("Network.disable", {})
# print("CDP Network events disabled.")
# except Exception as e:
# print(f"Error disabling network events: {e}")
print("Closing WebDriver...")
driver.quit()
print("Script finished.")
Explanation:
- Configuration: Set
TARGET_URL, BUTTON_SELECTOR, and AJAX_RESPONSE_URL_PATTERN to match the website you are testing. The AJAX_RESPONSE_URL_PATTERN is crucial for identifying the correct network response among potentially many.
ajax_response_details Dictionary: A global dictionary is used to store information about the target response once it's detected by the listener. This allows the main script flow to know when the event has occurred.
handle_network_response(response_data):
- This function is registered as a listener for the
Network.responseReceived CDP event.
- It receives event data containing details about every network response.
- It checks if the response URL contains your
AJAX_RESPONSE_URL_PATTERN.
- If a match is found and we haven't already stored a response (
requestId is None), it records the requestId, url, and status in the ajax_response_details dictionary. It doesn't fetch the body here to keep the listener fast and non-blocking.
get_ajax_response_body(driver, request_id):
- This function takes the
driver and the captured request_id.
- It executes the CDP command
Network.getResponseBody using driver.execute_cdp_cmd.
- It handles the response, checking if the body is Base64 encoded and decoding it if necessary. It assumes UTF-8 encoding for decoding.
- It returns the decoded response body as a string or
None if an error occurs or the body is empty.
- WebDriver Setup: Initializes the Chrome WebDriver. Options are set to potentially improve compatibility and avoid common automation detection flags.
- Enable CDP & Listener:
driver.execute_cdp_cmd("Network.enable", {}) tells the browser to start sending network-related events.
driver.add_cdp_listener("Network.responseReceived", handle_network_response) registers our callback function to receive these events. Crucially, this is done before navigating.
- Navigation & Click: The script navigates to the URL and waits for the button specified by
BUTTON_SELECTOR to be clickable before clicking it.
Remember to replace the placeholder configuration values with the actual details from the website you're automating.