javascript - puppeteer 网页异步代码未执行
问题描述
如果我“转到”包含异步代码的网页,它不会被执行,我不明白为什么。有人可以帮忙吗?
节点:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://127.0.0.1:8080/?code=ABC123&id=1', {
waitUntil: 'networkidle0',
});
await page.screenshot({ path: 'example.png' });
await browser.close();
})();
网页:
onmount = () => {
const params = new URLSearchParams(document.location.search);
const code = params.get('code');
// above lines are executed
// the code below is never executed
// search is an async function (not shown for brevity)
search(code).then(result => document.getElementById('title').textContent = result.title);
};
解决方案
您可以使用page.waitForFunction
来收听原始函数的预期结果。像这样,您可以确保只有在应用程序中解决了 Promise之后,下一步 ( page.screenshot
) 才会发生。
为此,您可以在顶部声明 URL 参数的值,以便稍后在将其作为参数传递给方法时比较其值。onmount
code=
waitForFunction
await page.waitForFunction(codeValue => document.querySelector('#title').textContent == codeValue, {}, codeValue);
例子:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const codeValue = 'ABC123';
await page.goto(`http://127.0.0.1:8080/?code=${codeValue}&id=1`, {
waitUntil: 'networkidle0',
});
await page.waitForFunction(codeValue => document.querySelector('#title').textContent == codeValue, {}, codeValue);
await page.screenshot({ path: 'example.png' });
await browser.close();
})();
推荐阅读
- c - 不同线程的相同线程 ID 的问题
- c# - 如何从一个 FBX 对象的动画(主摄像机的父级)切换到另一个 FBX 对象的动画
- file - 如何访问从 Windows 传输到 WSL-2 Ubuntu 的文件?
- javascript - fetch api - 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态
- jquery - 流星,$(...).openModal 不是函数
- python - 我想迭代两个循环,一个是列表,另一个是python中的语句
- c - 使用 rand() 在 C 中写入访问冲突错误
- c# - 将文件流式传输到 Azure Blob 存储?
- javascript - 在 Android Chrome 中运行 JavaScript 控制台(无电脑)
- python-3.x - discord.py - 停止玩游戏后删除角色