java解决cdp4j异常WebSocket connection url is required

java | 2020-02-22 10:49:27

linux中java使用cdp4j来操作谷歌chrome浏览器出错

异常信息

	at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
	at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
	at org.springframework.boot.loader.Launcher.launch(Launcher.java:51)
	at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52)
Caused by: io.webfolder.cdp.exception.CdpException: WebSocket connection url is required!
	at io.webfolder.cdp.Launcher.launchWithProcessBuilder(Launcher.java:308)
	at io.webfolder.cdp.Launcher.launch(Launcher.java:247)
	at com.xz.datacenter.datacollector.downloader.util.HTML2PDF.startLaunch(HTML2PDF.java:71)
	at com.xz.datacenter.datacollector.downloader.config.PdfPoolnit.run(PdfPoolnit.java:41)

 

原因分析

查看了一下保存地方的源代码

try {
                while(scanner.hasNext()) {
                    String line = scanner.nextLine().trim();
                    if (!line.isEmpty() && line.toLowerCase(Locale.ENGLISH).startsWith("devtools listening on")) {
                        int start = line.indexOf("ws://");
                        connection = new WebSocketConnection(line.substring(start, line.length()));
                        break;
                    }
                }

                if (connection == null) {
                    throw new CdpException("WebSocket connection url is required!");
                }
            } catch (Throwable var10) {
                try {
                    scanner.close();
                } catch (Throwable var9) {
                    var10.addSuppressed(var9);
                }

                throw var10;
            }

我猜是运行google-chrome命令时候出错了,然后我在linux直接运行chrome命令:

出现异常

# google-chrome
[29549:29549:0221/164919.340519:ERROR:zygote_host_impl_linux.cc(89)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.

意思是不能用root账号 运行非沙盒模式。

解决方法

方法1.添加参数--no-sandbox

# google-chrome --headless  --no-sandbox

方法2.新建一个用户再来使用命令或启动项目就没有问题了。

[test@slave202 pdfTest]$ google-chrome --headless --disable-gpu --print-to-pdf http://www.baidu.com
[0221/165412.594527:INFO:headless_shell.cc(619)] Written to file output.pdf.

这里将网页转为pdf,可以查看到output.pdf

登录后即可回复 登录 | 注册
    
关注编程学问公众号