正常模式下好好的,headless下就不行了,最后用网页截图发现了问题:
File scrFile = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
网站有浏览器版本检测,出了个特殊的页面。
根源就是没有设定好user-agent, 比如设定为下面的就可以了:
options.addArguments("--headless");
options.addArguments("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.0 Safari/537.36");
参考:
java - Cannot locate elements using headless mode Selenium - Stack Overflow