Phantom Js 不等待页面加载或所有 jquery 代码执行

Phantom Js does not wait for page to be load or all jquery code to be executed

我正在尝试将网页转换为 pdf,但网页正在加载,需要在页面上执行一些 jquery 函数以获取动态数据,这需要时间,因此页面加载在这里不是问题,而是动态的通过 jquery 添加数据让我很困扰。下面是我用来生成 pdf 的代码

String pathToPhantomJS = "/usr/bin/phantomjs" //path to your phantom js
String pathToRasterizeJS = "/home/tothenew/Desktop/rasterize.js" //path to your rasterize.js
String paperSize = "A4"
String url = "https://www.google.co.in/" //url of your web page to which you want to convert into pdf
File outputFile = File.createTempFile("sample", ".pdf") //file in which you want to save your pdf

//TODO: also do exception handling stuff . i am not doing this for simplicity

Process process = Runtime.getRuntime().exec(pathToPhantomJS + " " + pathToRasterizeJS + " " + url + " " + outputFile.absolutePath + " " + paperSize);
int exitStatus = process.waitFor(); //do a wait here to prevent it running for ever
if (exitStatus != 0) {
log.error("EXIT-STATUS - " + process.toString());
}

有什么方法 java 我可以告诉等待页面加载或我应该怎么做才能让 phantom js 仅在网页完全加载后捕获网页。

根据 this Stack Overflow post, this is a problem with phantomjs, not Java. However, If you are just trying to get a webpage as PDF, there are other options. After a bit of google-fu, I found this 网站,该网站提供了一个灵活的命令行工具和丰富的文档,以及一个 C 库。既然您已经在使用命令行工具来获取您的页面,那么在您的代码中实现这个工具应该没有问题。这是一个简短的例子:

    String wkhtmltopdf_path = "/usr/local/bin/wkhtmltopdf";
    String paperSize = "A4";
    String url = "https://www.google.com/";

    // This is where your output file is/was defined, now with error handling
    File outputFile = null; 
    try {
        //file in which you want to save your pdf
        outputFile = File.createTempFile("sample", ".pdf");
        System.out.println(outputFile.getAbsolutePath()); // Show output file path, remove this in production
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // This is where your process runs, with error handling
    Process process = null;
    try {
        process = Runtime.getRuntime().exec(String.format("%s -s %s %s %s", wkhtmltopdf_path, paperSize, url, outputFile.getAbsolutePath()));
    } catch (IOException e) {
        e.printStackTrace(); // Do your error handling here
    }

    // This is where your exitStatus and waitFor() was/is, with error handling
    int exitStatus = 0;
    try {
        //do a wait here to prevent it running for ever
        exitStatus = process.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace(); // Do your error handling here
    }
    if (exitStatus != 0) {
        // Do error handling here
    }