整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

java如何网页截屏?selenium来搞定

java如何网页截屏?selenium来搞定

需求一直有,今年比较多,如题,工作中遇到网页截图这样的需求,本着效果好,功能全又稳定的意图,去网上搜索相关技术,像HTML2Image、cssbox、selenium等,还有很多其他的技术,这篇文章主要说说我测试使用并能满足需求的cssbox,selenium。

Cssbox

CSSBox是一个用纯Java编写的(X)HTML/CSS渲染引擎。它的主要目的是提供关于呈现的页面内容和布局的完整和进一步可处理的信息。 但是,它也可以用于浏览Java Swing应用程序中呈现的文档。核心CSSBox库还可以用于获得所呈现的文档的位图或矢量(SVG)图像。 使用SwingBox包,CSSBox可以用作Java Swing应用程序中的交互式Web浏览器组件。

官网地址:http://cssbox.sourceforge.net/

使用

1引入maven依赖

<!--网站转换为图片cssbox-->
<dependency>
<groupId>net.sf.cssbox</groupId>
<artifactId>cssbox</artifactId>
<version>5.0.0</version>
</dependency>

2使用

@Test
public void cssboxTest(){
    try {
        ImageRenderer render=new ImageRenderer();
        //网络链接的html
        String url="https://www.zhangbj.com/p/524.html";
        //文件保存路径
        String path="C:\\Users\\Administrator\\Desktop"+File.separator+"html.png";
        FileOutputStream out=new FileOutputStream(new File(FilenameUtils.normalize(path)));
        //开始截屏
        render.renderURL(url, out);
    } catch (Exception e) {
    e.printStackTrace();
    }
}

3结果

样式可能出现问题,中文有时候乱码

Selenium

1引入依赖

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>

2相关准备

selenium+chromedriver谷歌驱动+chrome浏览器

1.注意谷歌驱动的版本要和谷歌浏览器的版本一样或者版本最相近

2.注意chromedriver谷歌驱动需要放在jdk安装目录下,具体路径为xxx/bin/chromedriver.exe,在linux和window中操作一样,这样切换系统是就无需改代码。

3.需要安装谷歌浏览器

谷歌驱动下载地址:https://registry.npmmirror.com/binary.html?path=chromedriver/

3使用

@Slf4j
public class Html2ImageUtil {
/**
* 将HTML转为图片,并保存至指定位置
* @param url 页面地址
* @param targetPath 保存地址(包含图片名,如 /images/test.png)
* @return
*/
public static String htmlToImage(String url, String targetPath) {
  if (StringUtils.isEmpty(url) || StringUtils.isEmpty(targetPath)) {
  throw new RuntimeException("截图失败!缺少必填项");
  }
  // 休眠时长
  Integer sleepTime=3 * 1000;
  // 无头模式
  System.setProperty("java.awt.headless", "true");
  //获取谷歌配置信息
  ChromeOptions chromeOptions=getChromeOptions();
  // 配置信息中有默认窗口大小,也可以单独设置窗口大小
  chromeOptions.addArguments("--window-size=1920,6000");
  //创建webdriver 谷歌驱动
  WebDriver driver=new ChromeDriver(chromeOptions);
  //也可以通过如下方式设置窗口大小
  // Dimension dimension=new Dimension(1000, 30);
  // driver.manage().window().setSize(dimension);
  try {
    //加载页面
    driver.get(url);
    //等待加载页面
    Thread.sleep(sleepTime);
    //截屏
    File srcFile=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    //保存到指定位置
    FileUtils.copyFile(srcFile, new File(FilenameUtils.normalize(targetPath)));
  } catch (InterruptedException | IOException e) {
  e.printStackTrace();
  throw new RuntimeException(e.getMessage());
  } finally {
  driver.quit();
  }
  log.info("截图成功!");
  return targetPath;
}
/**
* 获取chrome配置信息
* 注意 chromedriver谷歌驱动需要放在jdk安装目录下,具体路径为xxx/bin/chromedriver.exe ,在linux和window中操作一样
* @return
*/
public static ChromeOptions getChromeOptions() {
    ChromeOptions options=new ChromeOptions();
    //获取当前操作系统
    String os=System.getProperty("os.name");
    //获取jdk安装目录,需要提前将谷歌驱动放进jdk的bin目录下,在linux和window中操作一样
    String sysPath=System.getProperty("java.home").replace("jre", "bin");
    String chromeDriver=sysPath + File.separator+"chromedriver.exe";
    options.addArguments("disable-infobars");
    //设置为 headless 模式,不需要真实启动浏览器
    options.setHeadless(true);
    //options.addArguments("--headless");
    options.addArguments("--dns-prefetch-disable");
    options.addArguments("--no-referrers");
    options.addArguments("--disable-gpu");
    options.addArguments("--disable-audio");
    options.addArguments("--no-sandbox");
    options.addArguments("--ignore-certificate-errors");
    options.addArguments("--allow-insecure-localhost");
    options.addArguments("--window-size=1920,6000"); // 窗口默认大小
    String userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36";
    userAgent="user-agent=" + userAgent;
    options.addArguments(userAgent);
    // 设置chrome二进制文件
    options.setPageLoadStrategy(PageLoadStrategy.EAGER);
    // 设置驱动
    System.setProperty("webdriver.chrome.driver", chromeDriver);
    log.debug("结束获取chrome配置信息");
    return options;
}

测试

public static void main(String[] args) {
		htmlToImage("https://www.cnblogs.com/tester-ggf/p/12602211.html","C:\\Users\\Administrator\\Desktop\\aaa.png");
}

效果十分完美

总结

最完美的方案就是selenium+chromedriver谷歌驱动+chrome浏览器,无需多说,用吧。

您的赞和关注是对我创作的最大肯定谢谢大家!

前我曾写过如何将canvas图形转换成图片和下载canvas图像的方法,这些都是在为这个插件做技术准备。

技术路线很清晰,将网页的某个区域的内容生成图像,保持到canvas里,然后将canvas内容转换成图片,保存到本地,最后上传到微博。

我在网上搜寻到html2canvas这个能将指定网页元素内容生成canvas图像的javascript工具。这个js工具的用法很简单,你只需要将它的js文件引入到页面里,然后调用html2canvas()函数:

 html2canvas(document.body, {
     onrendered: function(canvas) {
         /* canvas is the actual canvas element,
            to append it to the page call for example
            document.body.appendChild( canvas );
         */
     }
 });

这个html2canvas()函数有个参数,上面的例子里传入的参数是document.body,这会截取整个页面的图像。如果你想只截取一个区域,比如对某个p或某个table截图,你就将这个p或某个table当做参数传进去。

我最终并没有选用html2canvas这个js工具,因为在我的实验过程中发现它有几个问题。

首先,跨域问题。我举个例子说明这个问题,比如我的网页网址是http://www.webhek.com/about/,而我在这个页面上有个张图片,这个图片并不是来自www.webhek.com域,而是来自CDN图片服务器www.webhek-cdn.com/images/about.jpg,那么,这张图片就和这个网页不是同域,那么html2canvas就无法对这种图片进行截图,如果你的网站的所有图片都放在单独的图片服务器上,那么用html2canvas对整个网页进行截图是就会发现所有图片的地方都是空白。

这个问题也有补救的方法,就是用代理:

 <!DOCTYPE html>
 <html>
     <head>
         <meta charset="utf-8">
         <title>html2canvas php proxy</title>
         <script src="html2canvas.js"></script>
         <script>
         //<![CDATA[
         (function() {
             window.onload=function(){
                 html2canvas(document.body, {
                     "logging": true, //Enable log (use Web Console for get Errors and Warnings)
                     "proxy":"html2canvasproxy.php",
                     "onrendered": function(canvas) {
                         var img=new Image();
                         img.onload=function() {
                             img.onload=null;
                             document.body.appendChild(img);
                         };
                         img.onerror=function() {
                             img.onerror=null;
                             if(window.console.log) {
                                 window.console.log("Not loaded image from canvas.toDataURL");
                             } else {
                                 alert("Not loaded image from canvas.toDataURL");
                             }
                         };
                         img.src=canvas.toDataURL("image/png");
                     }
                 });
             };
         })();
         //]]>
         </script>
     </head>
     <body>
         <p>
             <img alt="google maps static" src="http://maps.googleapis.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=12&size=800x600&maptype=roadmap&sensor=false">
         </p>
     </body>
 </html>

这个方法只能用在你自己的服务器里,如果是对别人的网页截图,还是不行。

试验的过程中还发现用html2canvas截屏出来的图像有时会出现文字重叠的现象。我估计是因为html2canvas在解析页面内容、处理css时不是很完美的原因。

最后,我在火狐浏览器的官方网站上找到了drawWindow()这个方法,这个方法和上面提到html2canvas不同之处在于,它不分析页面元素,它只针对区域,也就是说,它接受的参数是四个数字标志的区域,不论这个区域中什么地方,有没有页面内容。

 void drawWindow(
   in nsIDOMWindow window,
   in float x, 
   in float y,
   in float w,
   in float h,
   in DOMString bgColor,
   in unsigned long flags [optional]
 );

这个原生的JavaScript方法看起来非常的完美,正是我需要的,但这个方法不能使用在普通网页中,因为火狐官方发现这个方法会引起有安全漏洞,在这个bug修复之前,只有具有“Chrome privileges”的代码才能使用这个drawWindow()函数。

虽然有很大的限制,但周折一下还是可以用的,在我开发的火狐addon插件中,main.js就是具有“Chrome privileges”的代码。我在网上发现了一段火狐插件SDK里自带代码样例:

 var window=require('window/utils').getMostRecentBrowserWindow();
 var tab=require('tabs/utils').getActiveTab(window);
 var thumbnail=window.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
 thumbnail.mozOpaque=true;
 window=tab.linkedBrowser.contentWindow;
 thumbnail.width=Math.ceil(window.screen.availWidth / 5.75);
 var aspectRatio=0.5625; // 16:9
 thumbnail.height=Math.round(thumbnail.width * aspectRatio);
 var ctx=thumbnail.getContext("2d");
 var snippetWidth=window.innerWidth * .6;
 var scale=thumbnail.width / snippetWidth;
 ctx.scale(scale, scale);
 ctx.drawWindow(window, window.scrollX, window.scrollY, snippetWidth, snippetWidth * aspectRatio, "rgb(255,255,255)");
 // thumbnail now represents a thumbnail of the tab

这段代码写的非常清楚,只需要依据它做稍微的修改就能适应自己的需求。

这里小编是一个有着10年工作经验的前端高级工程师,关于web前端有许多的技术干货,包括但不限于各大厂的最新面试题系列、前端项目、最新前端路线等。需要的伙伴可以私信我

发送【前端资料】

就可以获取领取地址,免费送给大家。对于学习web前端有任何问题(学习方法,学习效率,如何就业)都可以问我。希望你也能凭自己的努力,成为下一个优秀的程序员

最近再做一个需求,需要对网页生成预览图,如下图


但是网页千千万,总不能一个个打开,截图吧;于是想着能不能使用代码来实现网页的截图。其实要实现这个功能,无非就是要么实现一个仿真浏览器,要么调用系统浏览器,再进行截图操作。

代码实现

1、启用线程Thread

  •  void startPrintScreen(ScreenShotParam requestParam) { Thread thread=new Thread(new ParameterizedThreadStart(do_PrintScreen)); thread.SetApartmentState(ApartmentState.STA); thread.Start(requestParam); if (requestParam.Wait) { thread.Join(); FileInfo result=new FileInfo(requestParam.SavePath); long minSize=1 * 1024;// 太小可能是空白圖,重抓 int maxRepeat=2;  while ((!result.Exists || result.Length <=minSize) && maxRepeat > 0) { thread=new Thread(new ParameterizedThreadStart(do_PrintScreen)); thread.SetApartmentState(ApartmentState.STA); thread.Start(requestParam); thread.Join(); maxRepeat--; } } }

    2、模拟浏览器WebBrowser

    •  void do_PrintScreen(object param) { try { ScreenShotParam screenShotParam=(ScreenShotParam)param; string requestUrl=screenShotParam.Url; string savePath=screenShotParam.SavePath; WebBrowser wb=new WebBrowser(); wb.ScrollBarsEnabled=false; wb.ScriptErrorsSuppressed=true; wb.Navigate(requestUrl); logger.Debug("wb.Navigate"); DateTime startTime=DateTime.Now; TimeSpan waitTime=new TimeSpan(0, 0, 0, 10, 0);// 10 second while (wb.ReadyState !=WebBrowserReadyState.Complete) { Application.DoEvents(); if (DateTime.Now - startTime > waitTime) { wb.Dispose(); logger.Debug("wb.Dispose() timeout"); return; } }
      wb.Width=screenShotParam.Left + screenShotParam.Width + screenShotParam.Left; // wb.Document.Body.ScrollRectangle.Width (避掉左右側的邊線); wb.Height=screenShotParam.Top + screenShotParam.Height; // wb.Document.Body.ScrollRectangle.Height; wb.ScrollBarsEnabled=false; wb.Document.Body.Style="overflow:hidden";//hide scroll bar var doc=(wb.Document.DomDocument) as mshtml.IHTMLDocument2; var style=doc.createStyleSheet("", 0); style.cssText=@"img { border-style: none; }";
      Bitmap bitmap=new Bitmap(wb.Width, wb.Height); wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height)); wb.Dispose(); logger.Debug("wb.Dispose()");
      bitmap=CutImage(bitmap, new Rectangle(screenShotParam.Left, screenShotParam.Top, screenShotParam.Width, screenShotParam.Height)); bool needResize=screenShotParam.Width > screenShotParam.ResizeMaxWidth || screenShotParam.Height > screenShotParam.ResizeMaxWidth; if (needResize) { double greaterLength=bitmap.Width > bitmap.Height ? bitmap.Width : bitmap.Height; double ratio=screenShotParam.ResizeMaxWidth / greaterLength; bitmap=Resize(bitmap, ratio); }
      bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Gif); bitmap.Dispose(); logger.Debug("bitmap.Dispose();"); logger.Debug("finish");
      } catch (Exception ex) { logger.Info($"exception: {ex.Message}"); } }

      3、截图操作

      •  private static Bitmap CutImage(Bitmap source, Rectangle section) { // An empty bitmap which will hold the cropped image Bitmap bmp=new Bitmap(section.Width, section.Height); //using (Bitmap bmp=new Bitmap(section.Width, section.Height)) { Graphics g=Graphics.FromImage(bmp);
        // Draw the given area (section) of the source image // at location 0,0 on the empty bitmap (bmp) g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
        return bmp; } }
        private static Bitmap Resize(Bitmap originImage, Double times) { int width=Convert.ToInt32(originImage.Width * times); int height=Convert.ToInt32(originImage.Height * times);
        return ResizeProcess(originImage, originImage.Width, originImage.Height, width, height); }

        完整代码


        •  public static string ScreenShotAndSaveAmazonS3(string account, string locale, Guid rule_ID, Guid template_ID) {  //新的Template var url=string.Format("https://xxxx/public/previewtemplate?showTemplateName=0&locale={0}&inputTemplateId={1}&inputThemeId=&Account={2}", locale, template_ID, account ); 
          var tempPath=Tools.GetAppSetting("TempPath");
          //路徑準備 var userPath=AmazonS3.GetS3UploadDirectory(account, locale, AmazonS3.S3SubFolder.Template); var fileName=string.Format("{0}.gif", template_ID); var fullFilePath=Path.Combine(userPath.LocalDirectoryPath, fileName); logger.Debug("userPath: {0}, fileName: {1}, fullFilePath: {2}, url:{3}", userPath, fileName, fullFilePath, url); //開始截圖,並暫存在本機 var screen=new Screen(); screen.ScreenShot(url, fullFilePath);
          //將截圖,儲存到 Amazon S3 //var previewImageUrl=AmazonS3.UploadFile(fullFilePath, userPath.RemotePath + fileName);
          return string.Empty; }


          • using System;using System.Collections.Generic;using System.Drawing;using System.IO;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;
            namespace PrintScreen.Common{ public class Screen { protected static NLog.Logger logger=NLog.LogManager.GetCurrentClassLogger();
            public void ScreenShot(string url, string path , int width=400, int height=300 , int left=50, int top=50 , int resizeMaxWidth=200, int wait=1) { if (!string.IsOrEmpty(url) && !string.IsOrEmpty(path)) { ScreenShotParam requestParam=new ScreenShotParam { Url=url, SavePath=path, Width=width, Height=height, Left=left, Top=top, ResizeMaxWidth=resizeMaxWidth, Wait=wait !=0 }; startPrintScreen(requestParam); } }
            void startPrintScreen(ScreenShotParam requestParam) { Thread thread=new Thread(new ParameterizedThreadStart(do_PrintScreen)); thread.SetApartmentState(ApartmentState.STA); thread.Start(requestParam); if (requestParam.Wait) { thread.Join(); FileInfo result=new FileInfo(requestParam.SavePath); long minSize=1 * 1024;// 太小可能是空白圖,重抓 int maxRepeat=2; while ((!result.Exists || result.Length <=minSize) && maxRepeat > 0) { thread=new Thread(new ParameterizedThreadStart(do_PrintScreen)); thread.SetApartmentState(ApartmentState.STA); thread.Start(requestParam); thread.Join(); maxRepeat--; } } }
            void do_PrintScreen(object param) { try { ScreenShotParam screenShotParam=(ScreenShotParam)param; string requestUrl=screenShotParam.Url; string savePath=screenShotParam.SavePath; WebBrowser wb=new WebBrowser(); wb.ScrollBarsEnabled=false; wb.ScriptErrorsSuppressed=true; wb.Navigate(requestUrl); logger.Debug("wb.Navigate"); DateTime startTime=DateTime.Now; TimeSpan waitTime=new TimeSpan(0, 0, 0, 10, 0);// 10 second while (wb.ReadyState !=WebBrowserReadyState.Complete) { Application.DoEvents(); if (DateTime.Now - startTime > waitTime) { wb.Dispose(); logger.Debug("wb.Dispose() timeout"); return; } }
            wb.Width=screenShotParam.Left + screenShotParam.Width + screenShotParam.Left; // wb.Document.Body.ScrollRectangle.Width (避掉左右側的邊線); wb.Height=screenShotParam.Top + screenShotParam.Height; // wb.Document.Body.ScrollRectangle.Height; wb.ScrollBarsEnabled=false; wb.Document.Body.Style="overflow:hidden";//hide scroll bar var doc=(wb.Document.DomDocument) as mshtml.IHTMLDocument2; var style=doc.createStyleSheet("", 0); style.cssText=@"img { border-style: none; }";
            Bitmap bitmap=new Bitmap(wb.Width, wb.Height); wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height)); wb.Dispose(); logger.Debug("wb.Dispose()");
            bitmap=CutImage(bitmap, new Rectangle(screenShotParam.Left, screenShotParam.Top, screenShotParam.Width, screenShotParam.Height)); bool needResize=screenShotParam.Width > screenShotParam.ResizeMaxWidth || screenShotParam.Height > screenShotParam.ResizeMaxWidth; if (needResize) { double greaterLength=bitmap.Width > bitmap.Height ? bitmap.Width : bitmap.Height; double ratio=screenShotParam.ResizeMaxWidth / greaterLength; bitmap=Resize(bitmap, ratio); }
            bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Gif); bitmap.Dispose(); logger.Debug("bitmap.Dispose();"); logger.Debug("finish");
            } catch (Exception ex) { logger.Info($"exception: {ex.Message}"); } }
            private static Bitmap CutImage(Bitmap source, Rectangle section) { // An empty bitmap which will hold the cropped image Bitmap bmp=new Bitmap(section.Width, section.Height); //using (Bitmap bmp=new Bitmap(section.Width, section.Height)) { Graphics g=Graphics.FromImage(bmp);
            // Draw the given area (section) of the source image // at location 0,0 on the empty bitmap (bmp) g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
            return bmp; } }
            private static Bitmap Resize(Bitmap originImage, Double times) { int width=Convert.ToInt32(originImage.Width * times); int height=Convert.ToInt32(originImage.Height * times);
            return ResizeProcess(originImage, originImage.Width, originImage.Height, width, height); }
            private static Bitmap ResizeProcess(Bitmap originImage, int oriwidth, int oriheight, int width, int height) { Bitmap resizedbitmap=new Bitmap(width, height); //using (Bitmap resizedbitmap=new Bitmap(width, height)) { Graphics g=Graphics.FromImage(resizedbitmap); g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(Color.Transparent); g.DrawImage(originImage, new Rectangle(0, 0, width, height), new Rectangle(0, 0, oriwidth, oriheight), GraphicsUnit.Pixel); return resizedbitmap; } }
            }
            class ScreenShotParam { public string Url { get; set; } public string SavePath { get; set; } public int Width { get; set; } public int Height { get; set; } public int Left { get; set; } public int Top { get; set; } /// <summary> /// 長邊縮到指定長度 /// </summary> public int ResizeMaxWidth { get; set; } public bool Wait { get; set; } }
            }

            效果

            完成,达到预期的效果。