>

乐百家前段:初探 Headless Chrome

- 编辑:乐百家599手机首页 -

乐百家前段:初探 Headless Chrome

终结录音

终止录音的点子,小编动用的是先暂停,之后供给试听也许别的的操作先施行,然后再将存款和储蓄流的数CEO度置为 0。

4.3.1家常接口调用

乐百家前段 1

图5

import {  stock_list} from '@/api'

const _this = this

stock_list(_this.req).then(response => {

        this.skuCateIdList = response

      })


怎么着在极限中使用

在Mac上接纳前,提出先绑定 Chrome 的外号

JavaScript

alias google-chrome="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"

1
alias google-chrome="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"

Linux下不要求绑定外号,从官网络下载最新版 Chrome 之后一贯运营以下命令就能够。

接下来,在终点中输入:

google-chrome --headless --disable-gpu --remote-debugging-port=9222

1
google-chrome --headless --disable-gpu --remote-debugging-port=9222  https://github.com

扩大 –disable-gpu 主借使为了挡住现阶段或然接触的失实。

那儿,Headless Chrome已经成功运转了。展开浏览器,输入 http://localhost:9222,你会看出如下的界面:乐百家前段 2

在极端中,大家还是能够做以下操作:

获得荧屏截图:

JavaScript

google-chrome --headless --disable-gpu --screenshot --window-size=1280,1696

1
google-chrome --headless --disable-gpu --screenshot --window-size=1280,1696 https://github.com

得到页面为PDF:

JavaScript

google-chrome --headless --disable-gpu --print-to-pdf

1
google-chrome --headless --disable-gpu --print-to-pdf https://github.com

打字与印刷页面DOM:

JavaScript

google-chrome --headless --disable-gpu --dump-dom

1
google-chrome --headless --disable-gpu --dump-dom https://github.com/

HTML5 录音的踩坑之旅

2017/12/25 · HTML5 · 录音

原来的小讲出处: 翁旺   

4.3.2导出多少接口调用

乐百家前段 3

图6


导出数据代码

this.isExport(this.req).then(res => {

            console.log(res)

            // 导出模拟链接点击

            const linkElement = document.createElement('a')

            try {

              var blob = new Blob([res.blob], { type: 'application/octet-stream' })

              var url = window.URL.createObjectURL(blob)

              linkElement.setAttribute('href', url)

              linkElement.setAttribute('download', res.filename)

              var clickEvent = new MouseEvent('click', {

                'view': window,

                'bubbles': true,

                'cancelable': false

              })

              linkElement.dispatchEvent(clickEvent)

            } catch (ex) {

              console.log(ex)

            }

          })


结束语:axios在vue中的使用方式大概就这几个。

小结

本文简要介绍了瞬间 Headless Chrome 在巅峰的用法,以至哪些接纳 Headless Chrome 获取截图、获取页面中的CSS和DOM、设置UA和Cookie、运行JS脚本、协作Karma 举办单元测量试验。接下来,就等着你探求越来越多关于 Headless Chrome 的用法了…

参考:

https://developers.google.com/web/updates/2017/04/headless-chrome
How to install and use Headless Chrome on OSX

1 赞 1 收藏 评论

乐百家前段 4

获得频率

JavaScript

getVoiceSize = analyser => { const dataArray = new Uint8Array(analyser.frequencyBinCount); analyser.getByteFrequencyData(dataArray); const data = dataArray.slice(100, 1000); const sum = data.reduce((a, b) => a b); return sum; };

1
2
3
4
5
6
7
getVoiceSize = analyser => {
const dataArray = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(dataArray);
const data = dataArray.slice(100, 1000);
const sum = data.reduce((a, b) => a b);
return sum;
};

实际能够参照

4.2编辑query.js中呼吁接口

乐百家前段 5

图4

import { fetch,custom } from '@/axios/api'

// 1. 库存查询

export function stock_list(query) {

  return fetch({

    url: '/inventory/stock/list/search',

    method: 'POST',

    params: query

  })

}


长途调控

在上文中汇报的都应用终端命令运转 Headless Chrome,下文以博取截图为例,尝试什么在程序里决定 Headless Chrome。

设置注重

JavaScript

npm install lighthouse chrome-remote-interface --save

1
npm install lighthouse chrome-remote-interface --save

完成截图的大概思路为:通过利用 lighthouse 运维 Headless Chrome,然后通过 chrome-remote-interface 长间距调整浏览器,使用 Page 监控页面包车型客车加载,使用 Emulation 模块调治视口缩放,最后生成一张截图。

JavaScript

const { ChromeLauncher } = require('lighthouse/lighthouse-cli/chrome-launcher') const chrome = require('chrome-remote-interface') const fs = require('fs') const deviceMetrics = { width: 1200, height: 800, deviceScaleFactor: 0, mobile: false, fitWindow: false } const screenshotMetrics = { width: deviceMetrics.width, height: deviceMetrics.height } let protocol let launcher function launchChrome () { const launcher = new ChromeLauncher({ port: 9222, autoSelectChrome: true, additionalFlags: ['--window-size=412,732', '--disable-gpu', '--headless'] }) return launcher.run().then(() => launcher) } function getScreenShot () { const { Page, Emulation } = protocol return Page.enable() .then(() => { Emulation.setDeviceMetricsOverride(deviceMetrics) // 配置浏览器尺寸 Emulation.setVisibleSize(screenshotMetrics) // 配置截图尺寸 Page.navigate({ url: '' }) return new Promise((resolve, reject) => { Page.loadEventFired(() => { resolve(Page.captureScreenshot({ format: 'jpeg', fromSurface: true })) }) }) }) .then(image => { const buffer = new Buffer(image.data, 'base64') return new Promise((resolve, reject) => { fs.writeFile('output.jpeg', buffer, 'base64', err => { if (err) return reject(err) resolve() }) }) }) } launchChrome() .then(Launcher => { launcher = Launcher return new Promise((resolve, reject) =>{ chrome(Protocol => { protocol = Protocol resolve() }).on('error', err => { reject(err) }) }) }) .then(getScreenShot) .then(() => { protocol.close() launcher.kill() }) .catch(console.error)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const { ChromeLauncher } = require('lighthouse/lighthouse-cli/chrome-launcher')
const chrome = require('chrome-remote-interface')
const fs = require('fs')
const deviceMetrics = {
  width: 1200,
  height: 800,
  deviceScaleFactor: 0,
  mobile: false,
  fitWindow: false
}
const screenshotMetrics = {
  width: deviceMetrics.width,
  height: deviceMetrics.height
}
let protocol
let launcher
 
function launchChrome () {
  const launcher = new ChromeLauncher({
    port: 9222,
    autoSelectChrome: true,
    additionalFlags: ['--window-size=412,732', '--disable-gpu', '--headless']
  })
  return launcher.run().then(() => launcher)
}
function getScreenShot () {
  const { Page, Emulation } = protocol
  return Page.enable()
    .then(() => {
      Emulation.setDeviceMetricsOverride(deviceMetrics) // 配置浏览器尺寸
      Emulation.setVisibleSize(screenshotMetrics) // 配置截图尺寸
      Page.navigate({ url: 'https://github.com/' })
      return new Promise((resolve, reject) => {
        Page.loadEventFired(() => {
          resolve(Page.captureScreenshot({ format: 'jpeg', fromSurface: true }))
        })
      })
    })
    .then(image => {
      const buffer = new Buffer(image.data, 'base64')
      return new Promise((resolve, reject) => {
        fs.writeFile('output.jpeg', buffer, 'base64', err => {
          if (err) return reject(err)
          resolve()
        })
      })
    })
}
launchChrome()
  .then(Launcher => {
    launcher = Launcher
    return new Promise((resolve, reject) =>{
      chrome(Protocol => {
        protocol = Protocol
        resolve()
      }).on('error', err => { reject(err) })
    })
  })
  .then(getScreenShot)
  .then(() => {
    protocol.close()
    launcher.kill()
  })
  .catch(console.error)

此间运用 lighthouse 提供的 ChromeLauncher 模块来调用 Chrome,即使计算机上设置了Chrome Canary,lighthouse 暗中同意会运营 Chrome Canary,可以将 autoSelectChrome 设置为false 然后活动选择使用什么版本。

透过 chrome-remote-interface 同盟 Headless Chrome,大家还足以做越来越多事情。

动用 CSS 和 DOM 模块,能够收获和装置页面中的 DOM 节点内容和 CSS 样式。

JavaScript

function getStyle () { const { Page, CSS, DOM } = protocol return Promise.all([ DOM.enable(), CSS.enable(), Page.enable() ]) .then(() => { Page.navigate({ url: '' }) return new Promise((resolve, _) => { Page.loadEventFired(() => { resolve(DOM.getDocument()) }) }) }) .then(res => res.root.nodeId) .then(nodeId => DOM.querySelector({ selector: '.btn-primary', nodeId })) .then(({ nodeId }) => CSS.getComputedStyleForNode({ nodeId })) .then(style => { console.log(style) }) }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function getStyle () {
  const { Page, CSS, DOM } = protocol
  return Promise.all([
      DOM.enable(),
      CSS.enable(),
      Page.enable()
    ])
    .then(() => {
      Page.navigate({ url: 'https://github.com/' })
      return new Promise((resolve, _) => {
        Page.loadEventFired(() => { resolve(DOM.getDocument()) })
      })
    })
    .then(res => res.root.nodeId)
    .then(nodeId => DOM.querySelector({ selector: '.btn-primary', nodeId }))
    .then(({ nodeId }) => CSS.getComputedStyleForNode({ nodeId }))
    .then(style => { console.log(style) })
}

利用 Runtime 模块,能够在页面运营时举办 JS 脚本。

JavaScript

function search () { const { Page, Runtime } = protocol return Promise.all([ Page.enable() ]) .then(() => { Page.navigate({ url: '' }) return new Promise((resolve, _) => { Page.loadEventFired(() => { resolve() }) }) }) .then(() => { const code = [ 'var input = document.querySelector('.s_ipt')', 'var btn = document.querySelector('#su')', 'input.value='123'' ].join(';') return Runtime.evaluate({ expression: code }) }) .then(() => { return new Promise((resolve, _) => { setTimeout(() => { resolve(Page.captureScreenshot({ format: 'jpeg', fromSurface: true })) }, 3000) }) }) .then(image => { const buffer = new Buffer(image.data, 'base64') return new Promise((resolve, reject) => { fs.writeFile('output.jpeg', buffer, 'base64', err => { if (err) return reject(err) resolve() }) }) }) }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function search () {
  const { Page, Runtime } = protocol
  return Promise.all([
      Page.enable()
    ])
    .then(() => {
      Page.navigate({ url: 'https://www.baidu.com/' })
      return new Promise((resolve, _) => {
        Page.loadEventFired(() => { resolve() })
      })
    })
    .then(() => {
      const code = [
        'var input = document.querySelector('.s_ipt')',
        'var btn = document.querySelector('#su')',
        'input.value='123''
      ].join(';')
      return Runtime.evaluate({ expression: code })
    })
    .then(() => {
      return new Promise((resolve, _) => {
        setTimeout(() => {
          resolve(Page.captureScreenshot({ format: 'jpeg', fromSurface: true }))
        }, 3000)
      })
    })
    .then(image => {
      const buffer = new Buffer(image.data, 'base64')
      return new Promise((resolve, reject) => {
        fs.writeFile('output.jpeg', buffer, 'base64', err => {
          if (err) return reject(err)
          resolve()
        })
      })
    })
}

行使 Network 模块,能够读取并安装 UserAgent 和 库克ie 等信息。

JavaScript

function setUAandCookie () { const { Page, Network } = protocol return Promise.all([ Network.enable(), Page.enable() ]) .then(() => { const userAgent = Network.setUserAgentOverride({ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.71 Safari/537.36" }) Network.setCookie({ url: '', name: 'test', value: '123', domain: '.github.com', path: '/', httpOnly: true }) Page.navigate({ url: '' }) return new Promise((resolve, _) => { Page.loadEventFired(() => { resolve() }) }) }) .then(() => { return Network.getCookies() }) .then(console.log) }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function setUAandCookie () {
  const { Page, Network } = protocol
  return Promise.all([
      Network.enable(),
      Page.enable()
    ])
    .then(() => {
      const userAgent =
      Network.setUserAgentOverride({ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.71 Safari/537.36" })
      Network.setCookie({
        url: 'https://github.com',
        name: 'test',
        value: '123',
        domain: '.github.com',
        path: '/',
        httpOnly: true
      })
      Page.navigate({ url: 'https://github.com/' })
      return new Promise((resolve, _) => {
        Page.loadEventFired(() => { resolve() })
      })
    })
    .then(() => {
      return Network.getCookies()
    })
    .then(console.log)
}

本文由乐百家前段发布,转载请注明来源:乐百家前段:初探 Headless Chrome