有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

浏览器显示的图像的java URL

我正在自动化我们组织的供应订购系统。在目前的(纸质)系统下,如果我们在网站上订购,我们需要附上一份显示所需商品的网页打印件。我正在编写的系统有一种上传扫描文件的方法,但我想让它成为一键操作,而不是打印网页,扫描它,然后上传扫描文件

我找到了this代码来将页面转换为图像,它确实可以工作,但创建的图像是基于html(这很有意义),而不是浏览器中显示的内容

例如,我正在查看以下项目:

Sample Amazon item


当我在代码中运行url时,返回的图像如下:

Returned image

该项目是使用servlet的JavaWeb。servlet代码:

    try {
        if (request.getParameter("formType").equalsIgnoreCase("addReference")) {
            String url = request.getParameter("url");
            BufferedImage bi = WebImage.create(url, 800, 600);
            File tmpFile = new File("c:/testimages/url2img.png");
            ImageIO.write(bi, "png", tmpFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

上面链接中的代码:

public abstract class WebImage {
    static class Kit extends HTMLEditorKit {
        @Override
        public Document createDefaultDocument() {
            HTMLDocument doc
                    = (HTMLDocument) super.createDefaultDocument();
            doc.setTokenThreshold(Integer.MAX_VALUE);
            doc.setAsynchronousLoadPriority(-1);
            return doc;
        }
    }
    public static BufferedImage create(String src, int width, int height) {
        BufferedImage image = null;
        JEditorPane pane = new JEditorPane();
        Kit kit = new Kit();
        pane.setEditorKit(kit);
        pane.setEditable(false);
        pane.setMargin(new Insets(0, 0, 0, 0));
        try {
            pane.setPage(src);
            image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.createGraphics();
            Container c = new Container();
            SwingUtilities.paintComponent(g, pane, c, 0, 0, width, height);
            g.dispose();
        } catch (Exception e) {
            System.out.println(e);
        }
        return image;
    }
}

有没有办法返回浏览器显示的url图像


共 (2) 个答案

  1. # 1 楼答案

    您使用的是Java,所以实际上有一个非常简单的解决方案。浏览器自动化是Selenium解决的一个(主要)问题

    下面是一些示例代码,请注意,如果页面加载时间比平时长,那么它并不是特别健壮,但它应该足以演示执行所需操作的必要步骤。另外请注意,如果需要无头运行,您可能希望查看JBrowserDriver而不是FireFox驱动程序

    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("https://www.amazon.com/I-Robot-Isaac-Asimov/dp/055338256X/ref=sr_1_2?ie=UTF8&qid=1496161782&sr=8-2&keywords=Asimov");
    // This move is necessary, the original file is temporary and gets deleted after java exists
    File resultingScreenshot = new File(System.getProperty("user.home"), "screenshot.png");
    Files.move(screenshotFile, resultingScreenshot);
    driver.quit();
    
    System.out.println("The screenshot is found here: " + resultingScreenshot);
    
  2. # 2 楼答案

    你需要一个完全成熟的浏览器,它支持大量的web标准(HTML、CSS、JS),才能实现你想要的。否则,您通常会使用不合格的web浏览器捕获渲染不良的图像

    看看BCqrstoO建议的硒

    此外,还有Chrome 59附带的Headless Chrome(Windows尚未推出) 或者PhantomJS不幸的是,它不再被维护,因此呈现最新和最棒页面的能力将随着时间的推移而减弱