使用 puppeteer 加载动态内容?
Load dynamic content with puppeteer?
我正在使用此代码获取页面数据。它有效,但我只获得了一次数据。
问题是这些数据每秒更新一次。我想在不重新加载页面的情况下获取它。
这是我想要的一个简单示例 - http://novinite.win/clock.php
有没有办法在不重新加载网页的情况下刷新结果?
const puppeteer = require('puppeteer');
(async () => {
const url = process.argv[2];
const browser = await puppeteer.launch({
args: ['--no-sandbox']
})
const page = await browser.newPage();
page.on('request', (request) => {
console.log(`Intercepting: ${request.method} ${request.url}`);
request.continue();
});
await page.goto(url, {waitUntil: 'load'});
const html = await page.content();
console.log(html);
browser.close();
})();
您可以 await
a Promise
that logs the current textContent
every 1000
ms (1 second) with setInterval
and resolves 在一定数量的间隔后(例如,10
间隔):
'use strict';
const puppeteer = require( 'puppeteer' );
( async () =>
{
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto( 'http://novinite.win/clock.php' );
await new Promise( ( resolve, reject ) =>
{
let i = 0;
const interval = setInterval( async () =>
{
console.log( await page.evaluate( () => document.getElementById( 'txt' ).textContent ) );
if ( ++i === 10 )
{
clearInterval( interval );
resolve( await browser.close() );
}
}, 1000 );
});
})();
示例结果:
19:24:15
19:24:16
19:24:17
19:24:18
19:24:19
19:24:20
19:24:21
19:24:22
19:24:23
19:24:24
我正在使用此代码获取页面数据。它有效,但我只获得了一次数据。 问题是这些数据每秒更新一次。我想在不重新加载页面的情况下获取它。 这是我想要的一个简单示例 - http://novinite.win/clock.php 有没有办法在不重新加载网页的情况下刷新结果?
const puppeteer = require('puppeteer');
(async () => {
const url = process.argv[2];
const browser = await puppeteer.launch({
args: ['--no-sandbox']
})
const page = await browser.newPage();
page.on('request', (request) => {
console.log(`Intercepting: ${request.method} ${request.url}`);
request.continue();
});
await page.goto(url, {waitUntil: 'load'});
const html = await page.content();
console.log(html);
browser.close();
})();
您可以 await
a Promise
that logs the current textContent
every 1000
ms (1 second) with setInterval
and resolves 在一定数量的间隔后(例如,10
间隔):
'use strict';
const puppeteer = require( 'puppeteer' );
( async () =>
{
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto( 'http://novinite.win/clock.php' );
await new Promise( ( resolve, reject ) =>
{
let i = 0;
const interval = setInterval( async () =>
{
console.log( await page.evaluate( () => document.getElementById( 'txt' ).textContent ) );
if ( ++i === 10 )
{
clearInterval( interval );
resolve( await browser.close() );
}
}, 1000 );
});
})();
示例结果:
19:24:15
19:24:16
19:24:17
19:24:18
19:24:19
19:24:20
19:24:21
19:24:22
19:24:23
19:24:24