Javascript 使用Selenium捕获网络XHR日志(带参数的请求/响应)
我试图用Selenium webdriver捕获网络XHR日志(chrome浏览器),这些日志通常显示请求(MethodType、标头、参数)和响应,但我只能获取客户端发送到服务器的api请求(无参数),搜索时我找到了以下代码,它只向我提供api请求:-Javascript 使用Selenium捕获网络XHR日志(带参数的请求/响应),javascript,java,selenium,selenium-webdriver,rest-assured-jsonpath,Javascript,Java,Selenium,Selenium Webdriver,Rest Assured Jsonpath,我试图用Selenium webdriver捕获网络XHR日志(chrome浏览器),这些日志通常显示请求(MethodType、标头、参数)和响应,但我只能获取客户端发送到服务器的api请求(无参数),搜索时我找到了以下代码,它只向我提供api请求:- LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER); for (LogEntry entry : logEntries) {
LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
for (LogEntry entry : logEntries) {
System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage())
}
但我还想得到客户端(浏览器)发送到服务器的所有参数以及响应。
*同样的功能如何在firefox上运行
提前谢谢 如果您使用Axios之类的库来进行XHR调用,则可以利用请求拦截器和响应拦截器作为中间件来拦截并最终记录每个XHR调用及其响应,而无需依赖无头浏览器界面 请求示例
client.interceptors.request.use(
req => {
// req contains your request data
},
err => Promise.reject(err),
);
client.interceptors.response.use(
response => response, // XHR Response
error => {
const originalRequest = error.config; // Error.config contains too the original request
// ...code
})
响应示例
client.interceptors.request.use(
req => {
// req contains your request data
},
err => Promise.reject(err),
);
client.interceptors.response.use(
response => response, // XHR Response
error => {
const originalRequest = error.config; // Error.config contains too the original request
// ...code
})
你可以用
下面的代码片段捕获所有请求和响应日志
// start the proxy
BrowserMobProxy proxy = new BrowserMobProxyServer();
proxy.start(0);
// get the Selenium proxy object
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
// start the browser up
WebDriver driver = new FirefoxDriver(capabilities);
// enable more detailed HAR capture, if desired (see CaptureType for the complete list)
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
// create a new HAR with the label "yahoo.com"
proxy.newHar("yahoo.com");
// open yahoo.com
driver.get("http://yahoo.com");
// get the HAR data
Har har = proxy.getHar();
任何har查看器都可以查看捕获的响应
我认为Selenium只能访问DOM,所以您需要使用javascript做一些奇怪的事情,这会让您的测试用例有点脏。DOM应该包含正在发送的所有内容。。。包含HTML5存储缓存。。。但是要获得标题,需要执行javascript。这里有一件事情似乎是可能的,那就是进入站点正在使用的框架,并对其进行修改以路由/复制请求。。。因此,如果他们使用jQuery,那么在AJAX调用中加入钩子,这些调用将返回或写入DOM所需的信息。