Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

node.js - How to get Puppeteer waitForNavigation Working after click

I am trying to get puppeteer to wait for the navigation to finish before moving on to the next statement. Based on the Docs for waitForNavigation() , the code should work below. but it just skips to the next statement and I have to use a workaround to wait for a specific URL in the response.

I have tried all the waituntil options as well
( load, domcontentloaded, networkidle0 and networkidle2 ) .

Any ideas how I could get that working properly is appreciated.

const browser = await puppeteer.launch({
  headless: false,
})
const page = await browser.newPage()
const home = page.waitForNavigation()
await page.goto(loginUrl)
await home

const login = page.waitForNavigation()
await page.type('#email', config.get('login'))
await page.type('#password', config.get('password'))
await page.click('#submitButton')
await login // << skips over this

// the following line is my workaround and it works , but ideally I don't want 
// to specify the expected "after" page each time I navigate
await page.waitForResponse(request => request.url() === 'http://example.com/expectedurl')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The function page.waitForNavigation() waits for navigation to begin and end.

The navigation has already been initiated with page.click().

Therefore, you can use Promise.all() to avoid the race condition between the mentioned functions:

const browser = await puppeteer.launch({
  headless: false,
});

const page = await browser.newPage();

await page.goto(loginUrl);

await page.type('#email', config.get('login'));
await page.type('#password', config.get('password'));

await Promise.all([
  page.click('#submitButton'),
  page.waitForNavigation({
    waitUntil: 'networkidle0',
  }),
]);

await browser.close();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...