背景是本地调试ChromeDriver截图正常,上linux系统后发现截图为黑屏
启动ChromeDriver的代码如下:
@Override
public StartDriverKeywordResult execute(StartDriverKeywordRequest request, OperationContext context) {
StartDriverKeywordResult result = new StartDriverKeywordResult();
ExChromeDriver client = null;
try {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
// 可以抽取关键字
client = new ExChromeDriver(options);
client.manage().deleteAllCookies();
client.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Dimension dimension = new Dimension(1400, 900);
client.manage().window().setSize(dimension);
log.info("@traceid:{},StartDriverKeyword success", EagleEye.getTraceId());
} catch (Exception ex) {
if (!Objects.isNull(client)) {
client.quit();
}
log.error("@traceid:{},StartDriverKeyword error:{}", EagleEye.getTraceId(), ex.getMessage());
result.setSuccess(false);
result.setDetailMessage("StartDriverKeyword error:" + ex.getMessage());
return result;
}
context.set("defaultDriver", client);
result.setDetailMessage("StartDriverKeyword success");
return result;
}
截图代码:
@Override
public SelfServicerGetOnLineKeywordResult execute(SelfServicerGetOnLineKeyworkRequest request,
OperationContext operationContext)
{
SelfServicerGetOnLineKeywordResult result = new SelfServicerGetOnLineKeywordResult();
browser = operationContext.getDefaultDriver();
try {
browser.get("https://www.baidu.com");
// 截图-1
browser.takeScreenShot("firstshot");
WebElement element = browser.findElement(By.xpath("//a[@name='tj_trnews']"));
String cityName = element.getText();
// 截图-2
browser.takeScreenShot("secondshot");
log.error("@traceid:{},SelfServicerGetOnLineKeyword#execute#cityName = {}", EagleEye.getTraceId(),
cityName);
result.setCityName(cityName);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
在mac系统上本地运行截图正常,但是在linux服务器上运行时发现截图为黑屏如下:
ChromeDriver启动时新增参数:options.addArguments("--disable-gpu")
后解决:
@Override
public StartDriverKeywordResult execute(StartDriverKeywordRequest request, OperationContext context) {
StartDriverKeywordResult result = new StartDriverKeywordResult();
ExChromeDriver client = null;
try {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--disable-gpu");
// 可以抽取关键字
client = new ExChromeDriver(options);
client.manage().deleteAllCookies();
client.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Dimension dimension = new Dimension(1400, 900);
client.manage().window().setSize(dimension);
log.info("@traceid:{},StartDriverKeyword success", EagleEye.getTraceId());
} catch (Exception ex) {
if (!Objects.isNull(client)) {
client.quit();
}
log.error("@traceid:{},StartDriverKeyword error:{}", EagleEye.getTraceId(), ex.getMessage());
result.setSuccess(false);
result.setDetailMessage("StartDriverKeyword error:" + ex.getMessage());
return result;
}
context.set("defaultDriver", client);
result.setDetailMessage("StartDriverKeyword success");
return result;
}
重新截图正常:
网友评论