java使用selenium示例
java网页爬虫感兴趣的可以了解下
pom.xml中配置如下
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.141.59</version> </dependency>
java代码如下
private ChromeOptions options = new ChromeOptions(); private ChromeDriver webDriver; /** * 创建浏览器驱动和打开一个浏览器窗口 * @return */ private ChromeDriver getChromeDriver(){ this.options.addArguments("--incognito"); List excludeSwitches=new ArrayList<String>(); Map<String, Object> prefs = new HashMap<String, Object>(); prefs.put("profile.managed_default_content_settings.images", 2); excludeSwitches.add("enable-automation"); this.options.setExperimentalOption("excludeSwitches",excludeSwitches); this.options.setExperimentalOption("prefs",prefs); File file = new File(System.getProperty("user.dir") + "\\Google\\Chrome\\Application\\chromedriver.exe"); if (file.exists()) { System.setProperty("webdriver.chrome.driver", file.getAbsolutePath()); } else { System.setProperty("webdriver.chrome.driver", dir); } log.info("当前读取驱动路径:{}", System.getProperty("webdriver.chrome.driver")); return new ChromeDriver(this.options); }
webdriver.chrome.driver用于指定谷歌浏览器驱动路径
--incognito参数为隐身模式打开浏览器
profile.managed_default_content_settings.images参数为无图模式
enable-automation参数为屏蔽浏览器自动化控制提示(有部分网站会检测当前页面是否为自动化控制,请勿关闭右上角提示,否则会失效)
打开指定网站
this.webDriver.get("https://baidu.com");
获取当前浏览器打开的所有页面元素
this.webDriver.getPageSource();