0
点赞
收藏
分享

微信扫一扫

等待waitFor

参考:​​https://zhaoqize.github.io/puppeteer-api-zh_CN/​​


//等待登陆按钮selector出现在页面中
await page.waitForSelector(SELECTOR.LOGIN_BTN)
//页面等待3秒
await page.waitForTimeout(3000)
//等待登录按钮XPath出现在页面中
await page.waitForXPath(XPATH.LOGIN_BTN)
await page.goto(url)
//等待页面加载完成
await page.waitForNavigation();

puppeteer——等待页面元素、等待函数、等待加载、请求、响应

waitForSelector与waitForXPath
waitForTimeout
waitForNavigation
waitForRequest
waitForResponse
waitForFunction

往往页面不会“唰”的一下马上加载好,甚至有时候网络影响会导致半天加载不出我们需要的页面元素,这里就需要waitFor全家桶了


  • waitForSelector与waitForXPath

大白话翻译:等待选择器/XPath

这两个其实说到底长得都差不多,都是右键copy就有选项是要selector还是XPath,用法一致,长相也亲兄弟,连参数都一样,更多更具体就不细说了可以自己查

但这里有一个非常好用的小点!

看到了什么?等待函数返回的居然是元素句柄??

所以就有了下面这种写法:

const login_btn = await page.waitForSelector(SELECTOR.LOGIN_BTN)

什么叫一举两得啊,用一次不仅等待、还获得了元素的句柄!

可以说是非常方便了


  • waitForTimeout

等待一段时间再继续向下执行,要注意的是这里的时间是毫秒做单位!


  • waitForNavigation​

这里官网API的原话是这么说的:

This resolves when the page navigates to a new URL or reloads.
It is useful for when you run code which will indirectly cause the page to navigate.

啥意思呢,意思就是:

如果你跳转了新URL或者重新加载页面了,用这个就能解决你的问题。

当你间接会导致页面跳转的时候用贼有效。

反正就记着——页面跳转完了,用来等加载


  • waitForRequest

字面上看,等待请求

使用方法,官网API中如下:

const firstRequest = await page.waitForRequest('http://example.com/resource');
const finalRequest = await page.waitForRequest(request =>
request.url() === 'http://example.com' && request.method() === 'GET');
return firstRequest.url();

参数是要等待的URL或者函数,等到了URL或函数的请求再继续


  • waitForResponse

同样字面看,等待响应

使用方法,官方API中如下:

const firstResponse = await page.waitForResponse('https://example.com/resource');
const finalResponse = await page.waitForResponse(response => response.url() === 'https://example.com' && response.status() === 200);
const finalResponse = await page.waitForResponse(async response => { return (await response.text()).includes('<html>') })
return finalResponse.ok();

参数同样是要等待响应的URL或者函数


  • waitForFunction

等待函数执行,官方API示例如下:

const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const watchDog = page.waitForFunction('window.innerWidth < 100');
await page.setViewport({width: 50, height: 50});
await watchDog;
await browser.close();
})();

简单说就是等一个函数执行了再继续,这个函数可以自定义

举报

相关推荐

0 条评论