Here's a Python Selenium code that clicks a button triggering an AJAX request and captures the response using JavaScript interception:
python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
# Initialize WebDriver
driver = webdriver.Chrome()
driver.get("YOUR_WEBSITE_URL") # Replace with your target URL
# Inject JavaScript to capture AJAX responses
driver.execute_script("""
window.ajaxResponses = [];
// Capture XMLHttpRequest
const xhrProto = XMLHttpRequest.prototype;
const origOpen = xhrProto.open;
xhrProto.open = function(method, url) {
this._url = url;
return origOpen.apply(this, arguments);
};
const origSend = xhrProto.send;
xhrProto.send = function(data) {
this.addEventListener('load', function() {
window.ajaxResponses.push({
type: 'XHR',
url: this._url,
response: this.responseText
});
});
return origSend.apply(this, arguments);
};
// Capture Fetch API
const origFetch = window.fetch;
window.fetch = function(resource, options) {
return origFetch.apply(this, arguments).then(response => {
const url = resource.url;
response.clone().text().then(body => {
window.ajaxResponses.push({
type: 'Fetch',
url: url,
response: body
});
});
return response;
});
};
""")
# Find and click the button (adjust selector as needed)
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "button#your-button-id"))
)
button.click()
# Wait for AJAX to complete (adjust time based on network speed)
time.sleep(2)
# Retrieve captured responses
responses = driver.execute_script("return window.ajaxResponses;")
for idx, resp in enumerate(responses, 1):
print(f"Response #{idx}:")
print(f"Type: {resp['type']}")
print(f"URL: {resp['url']}")
print(f"Response Body: {resp['response']}\n")
# Cleanup
driver.quit()
Key features:
- Injects JavaScript to intercept both XHR and Fetch API requests
- Captures response bodies and URLs
- Works with modern web applications
- Uses explicit waits for element interaction
- Handles multiple AJAX responses
Note: You need to:
- Replace
YOUR_WEBSITE_URL with the actual URL
- Update the button selector (
button#your-button-id)
- Adjust the
time.sleep(2) duration based on your network speed
- Handle potential CORS restrictions if working with cross-domain requests
For DOM-based responses (if the AJAX result is visible on the page), you can use this alternative approach:
python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("YOUR_WEBSITE_URL")
# Click button
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "button#your-button-id"))
)
button.click()
# Wait for and get updated content
result_element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, "div#result-container"))
)
print("AJAX Response:", result_element.text)
driver.quit()
Choose the first approach if you need raw response data, and the second approach if the response is rendered in the DOM.