RealA10N
RealA10N

Reputation: 130

Capture network requests using selenium

In the chrome dev tools, there is an option to capture network requests. I would like to know if there is any way to access the requests using selenium, in python.

I have searched this topic, But I could not find a solution. Solutions with other libraries are also appriciated!

Requests screenshot: devtools screenshot

Specific request info: enter image description here

Upvotes: 2

Views: 6105

Answers (1)

Mate Mrše
Mate Mrše

Reputation: 8394

Selenium 4 implements Chrome Dev Tools protocol support. However, it is still in alpha version, so keep that in mind if you intend to use it in the production code.

Here are some example usages from Automate the Planet that you might find helpful:

1. Intercepting Requests

EventHandler<RequestInterceptedEventArgs> requestIntercepted = (sender, e) =>
{
    Assert.IsTrue(e.Request.Url.EndsWith("jpg"));
};
            
RequestPattern requestPattern = new RequestPattern();
requestPattern.InterceptionStage = InterceptionStage.HeadersReceived;
requestPattern.ResourceType = ResourceType.Image;
requestPattern.UrlPattern = "*.jpg";
var setRequestInterceptionCommandSettings = new SetRequestInterceptionCommandSettings();
setRequestInterceptionCommandSettings.Patterns = new RequestPattern[] { requestPattern };
devToolssession.Network.SetRequestInterception(setRequestInterceptionCommandSettings);
devToolssession.Network.RequestIntercepted += requestIntercepted;

2. Listen to Console Logs

EventHandler<MessageAddedEventArgs> messageAdded = (sender, e) =>
{
    Assert.AreEqual("BELLATRIX is cool", e.Message);
};
devToolssession.Console.Enable();
devToolssession.Console.ClearMessages();
devToolssession.Console.MessageAdded += messageAdded;
_driver.ExecuteScript("console.log('BELLATRIX is cool');");

NOTE: This is Java implementation, you should edit it for Python.

Upvotes: 1

Related Questions