Intercept and modify requests and responses
masterSelenium Wire allows you to modify network traffic on the fly using interceptors.
- Request Interceptor: A function that accepts a single argument (
request). Set it viadriver.request_interceptor. - Response Interceptor: A function that accepts two arguments (
request,response). Set it viadriver.response_interceptor.
Important Patterns:
- Replacing Headers: Since
request.headersallows duplicates, always usedel request.headers['header-name']before setting a new value to ensure you are replacing rather than appending. - Updating Parameters: Request parameters are held in a regular dictionary. To update them, you must read the dictionary, modify it, and write it back to
request.params. - Updating JSON Bodies: For POST requests with JSON, you must decode the
request.body(bytes) to a string, parse it, modify it, and then re-encode it back to bytes. Remember to update theContent-Lengthheader manually after modifying the body.
def interceptor(request):
params = request.params
params['foo'] = 'bar'
request.params = params
driver.request_interceptor = interceptor
driver.get(...)
# To unset an interceptor:
del driver.request_interceptor
del driver.response_interceptor