Skip to content

Instantly share code, notes, and snippets.

@aneasystone
Created February 28, 2018 06:58
Show Gist options
  • Save aneasystone/200697a4702d7539c9483bbfb67334d6 to your computer and use it in GitHub Desktop.
Save aneasystone/200697a4702d7539c9483bbfb67334d6 to your computer and use it in GitHub Desktop.
import net.lightbody.bmp.BrowserMobProxy;
import net.lightbody.bmp.BrowserMobProxyServer;
import net.lightbody.bmp.client.ClientUtil;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Test {
public void action() throws Exception {
// 启动代理,用于拦截请求
BrowserMobProxy proxyServer = new BrowserMobProxyServer();
proxyServer.start(0);
// 拦截请求,对请求参数进行修改,或者直接返回伪造响应
proxyServer.addRequestFilter((request, contents, messageInfo) -> {
System.out.println("请求开始:" + messageInfo.getOriginalUrl());
return null;
});
// 拦截请求响应,对响应进行修改
proxyServer.addResponseFilter((response, contents, messageInfo) -> {
System.out.println("请求结束:" + messageInfo.getOriginalUrl());
if (messageInfo.getOriginalUrl().contains("remote/searchFlights")) {
System.out.println("响应" + contents.getTextContents());
}
});
// 启动Chrome浏览器
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
options.addArguments("disable-popup-blocking");
options.setBinary("D:\\Chrome32_51.0.2704.84\\chrome.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
capabilities.setCapability(CapabilityType.PROXY, ClientUtil.createSeleniumProxy(proxyServer));
ChromeDriver driver = new ChromeDriver(capabilities);
// 访问首页,设置浏览器cookie
driver.get("http://www.tuniu.com/flight/intel/sha-bkk");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment