如何将variables传递给Puppeteer page.on?

如果我有这个

page.on('response', this.extractImages);

第一个问题:如何将其他variables传递给this.extractImages函数? 该函数被定义为extractImages(...args)args只是这个:

 [ Response { _client: Session { domain: null, _events: [Object], _eventsCount: 15, _maxListeners: undefined, _lastId: 9, _callbacks: Map {}, _connection: [Object], _targetId: '3879dfee-f3de-48a8-a735-ac3b8cb4110e', _sessionId: '3879dfee-f3de-48a8-a735-ac3b8cb4110e:1' }, _request: Request { _client: [Object], _requestId: '39213.259', _interceptionId: null, _interceptionHandled: false, _response: [Circular], _completePromiseFulfill: [Function], _completePromise: [Object], url: 'https://cm.g.doubleclick.net/pixel?google_nid=rubicon&google_cm&google_sc&google_awbid', method: 'GET', postData: undefined, headers: [Object] }, _contentPromise: null, headers: Map { 'pragma' => 'no-cache', 'date' => 'Sat, 09 Sep 2017 06:46:10 GMT', 'server' => 'HTTP server (unknown)', 'status' => '302', 'p3p' => 'policyref="https://googleads.g.doubleclick.net/pagead/gcn_p3p_.xml", CP="CURa ADMa DEVa TAIo PSAo PSDo OUR IND UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"', 'location' => 'https://pixel.rubiconproject.com/tap.php?v=7751&nid=2249&expires=30&put=CAESEBK_unCwxxtI7mj-7CUjh3g&google_cver=1', 'cache-control' => 'no-cache, must-revalidate', 'content-type' => 'text/html; charset=UTF-8', 'alt-svc' => 'quic="googleads.g.doubleclick.net:443"; ma=2592000; v="39,38,37,35",quic=":443"; ma=2592000; v="39,38,37,35"', 'content-length' => '326', 'x-xss-protection' => '1; mode=block', 'expires' => 'Fri, 01 Jan 1990 00:00:00 GMT' }, status: 302, ok: false, url: 'https://cm.g.doubleclick.net/pixel?google_nid=rubicon&google_cm&google_sc&google_awbid' } ] 

第二个问题:如何从page.on触发的函数返回(在这种情况下: this.extractImages )?

如果你想从目标HTML页面提取图像,这是做错的地方。

当你写

 page.on('response', this.extractImages); 

this.extractImages将调用this.extractImages并传递给它一个Response类的对象,其中包含有关服务器如何响应请求的各种信息,最重要的是标题。 (这正是你在问题中所performance的)。 但是它不包含HTML。


要parsing页面中的所有数据,您宁愿等待其完全加载,然后使用page.evaluate来提取所需的任何信息:

 'use strict'; const puppeteer = require('puppeteer'); const url = 'https://example.com'; const extractImages = (selector) => { const imgs = Array.from(document.querySelectorAll(selector)); return imgs.map(img => img.src); } const selector = '#some .content img'; (async() => { const browser = await puppeteer.launch() const page = await browser.newPage(); await page.goto(url, {waitUntil: 'networkidle'}); const images = await page.evaluate(extractImages, selector); console.log(images.join('\n')); browser.close(); })(); 

从这个例子改编,更多的例子可以在这里find。

在puppeteer中,还有更多的方法与目标页面进行交互,但我个人发现page.evaluate更合乎逻辑,因为它明确地将节点脚本上下文与目标页面的上下文分开,就像在PhantomJS中一样。