Search code examples
c#selenium-webdriverselenium-chromedriverxmlhttprequesthttp-headers

Get request URL from the header in the Network Tab, and store into string


I am using Selenium to test generating a report based on selected parameters. When my test clicks the 'Get Report' button, a report is generated, but as an image, so I can't check that the parameters that I've previously selected, are the ones present via web elements, as would usually do in Selenium. What I can do is get the API response body, and assert against that, but I have to hard-code the request URL, because I can't find a way of dynamically fetching it from the Network tab post clicking the button. The request URL has a query string including date and time, so I can't just have it hard-coded as a string, I need to be able to fetch it dynamically, store it into a string, that I can then pass into my function that then gets the API response.

Is this possible to do, and if so, what is the correct method/way of doing it in C#?


Solution

  • Just wanted to update this, just in case its a question that somebody else needs an answer to, but I managed to find the solution: What the code is doing is collecting all of the event data happening at the point in my test. The static void 'Session_DevToolsEventReceived' then loops until it finds the "documentURL" which is the event name that I'm looking for.

            IDevTools devTools = (IDevTools)driver;
            DevToolsSession session = devTools.GetDevToolsSession();
            var domains = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
            await domains.Network.Enable(new EnableCommandSettings());
            domains.Network.Session.DevToolsEventReceived += Session_DevToolsEventReceived;
            driver.FindElement(By.CssSelector("getResultsBtn")).Click();
    
            static void Session_DevToolsEventReceived(object? sender, DevToolsEventReceivedEventArgs e)
            {
                _url ??= e.EventData["documentURL"]?.ToString();
            }