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

时间:2017-09-29 14:09:38

标签: java phantomjs

我正在尝试将网页转换为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我可以告诉等待页面加载或我应该怎么做,幻影js将捕获网页只有在它完全加载后。

1 个答案:

答案 0 :(得分:0)

根据this Stack Overflow帖子,这是phantomjs的问题,而不是Java。但是,如果您只是尝试将网页设为PDF,则还有其他选项。经过一段时间的google-fu之后,我找到了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
    }