WeChat applet parsing web content

巴扎黑
Release: 2017-09-06 10:43:12
Original
1935 people have browsed it

微信小程序 解析网页内容详解

最近在写一个爬虫,需要将网页进行解析供微信小程序使用。文字和图片解析都好说,小程序也有对应的text和image标签可以呈现。而更复杂的,比如表格,则比较棘手,不管是服务端解析还是小程序呈现都很费劲,也很难覆盖所有情况。于是我想,将表格对应的HTML代码转成图片,不失为一种变通的方法。

这里我们采用node-webshot模块,它对PhantomJS进行了轻量封装,可以轻松地将网页以截图形式保存下来。

首先安装Node.js和PhantomJS,然后新建一个js文件,加载node-webshot模块:

const webshot = require('webshot');
Copy after login

定义选项:

const options = {
  // 浏览器窗口
  screenSize: {
    width: 755,
    height: 25
  },
  // 要截图的页面文档区域
  shotSize: {
    height: 'all'
  },
  // 网页类型
  siteType: 'html'
};
Copy after login

这里,浏览器窗口的宽度要根据网页情况合理设置,高度可以设置为一个很小的数值,然后页面文档区域的高度一定要设置为all,宽度默认为窗口宽度,这样就可以把表格以最小的尺寸完整截图。

接下来,定义html字符串:

let html = "target rich text html code, eg: <table>...</table>";
Copy after login

注意,里面的HTML代码一定要去掉换行符,并将双引号替换为单引号。

最后,截图:

webshot(html, 'demo.png', options, (err) => {
  if (err)
    console.log(`Webshot error: ${err.message}`);
});
Copy after login

这样,就实现了从HTML代码到本地图片的转换,后续可以上传到七牛云等。不管是服务端的解析,还是小程序的呈现,都没有什么难度了...

The above is the detailed content of WeChat applet parsing web content. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!