環境准備
-
selenium-java 依賴
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.0.0-alpha-6</version> </dependency>
-
谷歌驅動准備
版本對應所運行的環境瀏覽器的版本(demo 機器上的谷歌瀏覽器是93版本所以對應下載了93的win驅動)
代碼編寫
-
chromeConfig.java
@Component public class ChromeConfig { public static ChromeOptions getOptions() { ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.setHeadless(true); chromeOptions.addArguments("--no--sandbox","--disable-gpu","--disable-dev-shm-usage", "blink-settings=imagesEnabled=false","--disable-javascript","--disable-plugins"); return chromeOptions; } }
-
ChromeInit.java
@Component public class ChromeInit implements ApplicationRunner { public ChromeDriver driverweb; @Override public void run(ApplicationArguments args) throws Exception { driverweb=getDriver(); } public static ChromeDriver getDriver() { //目錄可以寫進配置文件讀取,這里方便測試直接寫入了 String path = "D:\\chromedriver.exe"; System.setProperty("webdriver.chrome.driver",path); return new ChromeDriver(getOptions()); } }
-
CityInfoService.java
@Service public class CityInfoService { public static final String strUrl = "這里填寫地址"; @Resource ChromeInit chromeInit; /** * @param info url / code * @return * @throws InterruptedException */ public Map<String, Object> getInformation(Map<String, String> info) throws InterruptedException { HashMap<String, Object> map = new HashMap<>(); String url = info.get("url"); String code = info.get("code"); if ("" != code && code != null) { url = strUrl + code; } if ("".equals(url) || url == null) { map.put("code", 0); map.put("content", "url 或 code 必填其一"); map.put("data", null); return map; } chromeInit.driverweb.get(url); Thread.sleep(100); //這里是獲取瀏覽器session信息 JSONObject jsonObject = JSON.parseObject(chromeInit.driverweb.getSessionStorage().getItem("key")); map.put("code", 1); map.put("content", "操作成功"); map.put("data", jsonObject); return map; } }
總結
依據瀏覽器自動化工具selenium 實現模擬用戶操作 ,從而可以爬取頁面信息,編寫自動操作腳本實現測試等。
效率上和其他方法比略有不足,該方法並不常用。
在匹配 selenium 和驅動 瀏覽器版本時要注意,版本不對會導致程序無法運行,增加排除負擔。