如何在C#中读取WS Chrome日志中的Web Socket消息

1zmg4dgp  于 11个月前  发布在  Go
关注(0)|答案(3)|浏览(136)

我想从Chrome检查中读取Web Socket消息。我尝试使用Selenium但无法成功。请帮助我们使用C#读取。
enter image description here

uqxowvwt

uqxowvwt1#

请检查下面的代码。它捕获并打印客户端/服务器之间发送/接收的消息。然而,此代码是Java代码

import org.json.JSONObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.util.logging.Level;

public class WebSocketLogging {
    
    private static WebDriver driver;
    
    public static void main(String[] args) throws InterruptedException {
        LoggingPreferences loggingprefs = new LoggingPreferences();
        loggingprefs.enable(LogType.PERFORMANCE, Level.ALL);

        DesiredCapabilities cap = new DesiredCapabilities().chrome();
        cap.setCapability(CapabilityType.LOGGING_PREFS, loggingprefs);
        
        System.setProperty("webdriver.chrome.driver", "C:\\Sarabjeet\\Box\\chromedriver.exe");

        driver = new ChromeDriver(cap);
        driver.navigate().to("https://web-demo.adaptivecluster.com/");
        Thread.sleep(5000);
        LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);

        driver.close();
        driver.quit();
        logEntries.forEach(entry->{
            JSONObject messageJSON = new JSONObject(entry.getMessage());
            String method = messageJSON.getJSONObject("message").getString("method");
            if(method.equalsIgnoreCase("Network.webSocketFrameSent")){
                System.out.println("Message Sent: " + messageJSON.getJSONObject("message").getJSONObject("params").getJSONObject("response").getString("payloadData"));
            }else if(method.equalsIgnoreCase("Network.webSocketFrameReceived")){
                System.out.println("Message Received: " + messageJSON.getJSONObject("message").getJSONObject("params").getJSONObject("response").getString("payloadData"));
            }
        });
    }

}

字符串

bis0qfac

bis0qfac2#

安装包AsyncChromeDriver

var asyncChromeDriver = new AsyncChromeDriver();
await asyncChromeDriver.CheckConnected();
var command = new Zu.ChromeDevTools.Network.EnableCommand();
await asyncChromeDriver.DevTools.Network.Enable(command);
var webDriver = new WebDriver(asyncChromeDriver);
await webDriver.Options().Timeouts.SetImplicitWait(TimeSpan.FromSeconds(1));
await webDriver.GoToUrl("WebsiteUrl");               
asyncChromeDriver.DevTools.Network.SubscribeToWebSocketFrameReceivedEvent(item =>
   {
      Log your Data
   });

字符串

zysjyyx4

zysjyyx43#

下面是如何使用Selenium读取websockets框架,你可以做以下事情。

设置监听器逻辑

var driver = new ChromeDriver(options);      

IDevTools devTools = driver as IDevTools;
var session = devTools.GetDevToolsSession();

// May need to use a different version of DevTools besides V119
var networkAdapter = session.GetVersionSpecificDomains<OpenQA.Selenium.DevTools.V119.DevToolsSessionDomains>().Network;

networkAdapter.WebSocketCreated += NetworkAdapter_WebSocketCreated;
networkAdapter.WebSocketFrameReceived += NetworkAdapter_WebSocketFrameReceived;
var websocketCommandSettings = new OpenQA.Selenium.DevTools.V119.Network.EnableCommandSettings();
networkAdapter.Enable(websocketCommandSettings);

字符串

查找连接

private void NetworkAdapter_WebSocketCreated(object sender, OpenQA.Selenium.DevTools.V119.Network.WebSocketCreatedEventArgs e)
{
  if (!e.Url.Contains("wss://whatever.url.you.want.to.filter.on"))
  {
    Debug.WriteLine($"Ignoring the following Request URL({e.Url}), Request Id{e.RequestId}");
    
    return;
  }

  StoredRequestId = e.RequestId;
  Debug.WriteLine($"YAY!!! Received the Websocket connection of interest, Request URL({e.Url}), Request Id{e.RequestId}");
}

使用框架

private void NetworkAdapter_WebSocketFrameReceived(object sender, OpenQA.Selenium.DevTools.V119.Network.WebSocketFrameReceivedEventArgs e)
 {
   // Note:the StoredRequestId would need to be a class private variable/property
   if (e.RequestId != StoredRequestId)
   {
     return;
   }
   Debug.WriteLine($"Received Websocket Frame for requestId({e.RequestId}), contains: {e.Response.PayloadData}");
 }


注意事项:这个解决方案可能可以改进,以过滤请求,就像你可以用Fetch API过滤一样。但是我还没有研究过,也没有找到一个例子。

相关问题