😺
Selenium 4でAjax通信のレスポンスを確認する例(Java)
Selenium 4からChromeDevTools経由でAjax通信内容をキャプチャすることが出来ます。
maven
org.seleniumhq.selenium:selenium-chrome-driver:4.1.1
org.seleniumhq.selenium:selenium-devtools-v96:4.1.1
org.seleniumhq.selenium:selenium-java:4.1.1
org.seleniumhq.selenium:selenium-support:4.1.1
ローカルのChromeDriverを利用する場合の例
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v96.network.Network;
import org.openqa.selenium.remote.Augmenter;
import java.net.MalformedURLException;
import java.util.Optional;
public class TestMain {
public static void main(String[] args) throws MalformedURLException {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver = new Augmenter().augment(driver);
DevTools devTools = ((HasDevTools) driver).getDevTools();
devTools.createSession();
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
devTools.addListener(Network.responseReceived(),
entry -> {
System.out.println("Request Id:"+entry.getRequestId() + "\t" + entry.getResponse().getUrl());
Network.GetResponseBodyResponse res = devTools.send(Network.getResponseBody(entry.getRequestId()));
System.out.println(res.getBody());
});
driver.get("https://github.com/");
driver.quit();
}
}
Selenium DockerなどGridサーバを経由する場合の例
※http://192.168.24.42:4444/wd/hub を置き換えて下さい
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v96.network.Network;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Optional;
public class Main {
public static void main(String[] args) throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setBrowserName("chrome");
WebDriver driver = new RemoteWebDriver(new URL("http://192.168.24.42:4444/wd/hub"), caps);
driver = new Augmenter().augment(driver);
DevTools devTools = ((HasDevTools) driver).getDevTools();
devTools.createSession();
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
devTools.addListener(Network.responseReceived(),
entry -> {
System.out.println("Request Id:"+entry.getRequestId() + "\t" + entry.getResponse().getUrl());
Network.GetResponseBodyResponse res = devTools.send(Network.getResponseBody(entry.getRequestId()));
System.out.println(res.getBody());
});
driver.get("https://github.com/");
driver.quit();
}
}
Discussion