配置也支持模拟手机浏览器!
String url = "";
// 模拟浏览器配置
ChromeOptions options = new ChromeOptions();
// 配置日志可获取响应头信息
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
// 不显示浏览器
options.addArguments("headless");
// 禁用沙盒nage
options.addArguments("no-sandbox");
// 禁用GPU加速
options.addArguments("disable-gpu");
// 配置代理
String proxyIpAndPort = "1.2.3.4:3128";
final Proxy proxy = new Proxy();
proxy
// 配置http代理
.setHttpProxy(proxyIpAndPort)
// 配置https代理
.setSslProxy(proxyIpAndPort)
// 配置ftp代码
.setFtpProxy(proxyIpAndPort);
// 开启代理
options.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY, true);
// 只代理当前ChromeDriver流量
options.setCapability(CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC, true);
// 把代理加入ChromeDriver配置
options.setCapability(CapabilityType.PROXY, proxy);
// 模拟手机
Map<String, String> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceName", "Nexus 5");
options.setExperimentalOption("mobileEmulation", mobileEmulation);
// 创建浏览器
ChromeDriver driver = new ChromeDriver(options);
// 访问url
driver.get(url);
// 获取网页源码
String pageSource = driver.getPageSource();
// 操作网页元素
// driver.findElement()
// 获取响应日志
LogEntries logEntries = driver.manage().logs().get("performance");
// 获取所有响应头, 根据需要遍历获取即可
List<LogEntry> all = logEntries.getAll();