node.js - 如何使用 click 和 waitForNavigation?
问题描述
#!/usr/bin/env node
// vim: set noexpandtab tabstop=2:
const puppeteer = require('puppeteer');
const fs = require('fs').promises;
const cookies_json_file = process.argv[2];
const url = process.argv[3];
const timeout = parseInt(process.argv[4], 10);
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const cookiesString = await fs.readFile(cookies_json_file);
const cookies = JSON.parse(cookiesString);
await page.setCookie.apply(page, cookies);
try {
await page.goto(url, { waitUntil: 'networkidle2', timeout: timeout });
const content = await page.content();
page.on('response', async response => {
if(response.url().startsWith('https://www.genecards.org/gene/api/data/Enhancers?geneSymbol=')) {
response.buffer().then(function(data) {
fs.writeFile('/dev/stdout', data);
});
}
});
const linkHandlers = await page.$x('//div[@data-ga-category = "GeneHancer"]//a[@data-role = "show-all"]');
if (linkHandlers.length > 0) {
await Promise.all([
linkHandlers[0].click()
, page.waitForNavigation({waitUntil: 'networkidle2', timeout: timeout})
]);
} else {
throw new Error("Link not found");
}
} catch (e) {
console.error(e);
process.exit(1);
} finally {
await browser.close();
}
})();
我有上面的main.js
。
$ ./main.js cookies.json 'https://www.genecards.org/cgi-bin/carddisp.pl?gene=BSCL2' 30000
当我使用上面的命令运行时,我得到了这个错误。有人知道如何修复错误吗?谢谢。
TimeoutError: Navigation Timeout Exceeded: 30000ms exceeded
at /usr/local/lib/node_modules/puppeteer/lib/LifecycleWatcher.js:142:21
-- ASYNC --
at Frame.<anonymous> (/usr/local/lib/node_modules/puppeteer/lib/helper.js:110:27)
at Page.waitForNavigation (/usr/local/lib/node_modules/puppeteer/lib/Page.js:649:49)
at Page.<anonymous> (/usr/local/lib/node_modules/puppeteer/lib/helper.js:111:23)
at main.js:33:12
at processTicksAndRejections (internal/process/task_queues.js:89:5) {
name: 'TimeoutError'
}
```
解决方案
您需要通过将 timeout 参数设置为 0 来禁用超时。默认值为 30 秒(您也将其作为示例中的命令行参数传递),因此它的行为符合预期并引发异常,因为超时超过了默认值或用户提供的值 30000 毫秒。
page.waitForNavigation({waitUntil: 'networkidle2', timeout: 0})
您还可以从命令行将参数作为参数传递,这样最好不要对值进行硬编码:
$ ./main.js cookies.json 'https://www.genecards.org/cgi-bin/carddisp.pl?gene=BSCL2' 0
推荐阅读
- spring-boot - Springboot Kafka - 消费者幂等性
- r - 我正在编写我的第一个闪亮的应用程序。我有两个错误:“&”对因素没有意义,“职业”在应用程序中找不到
- javascript - 具有多个文本文件输入的滚动选框
- c# - UWP 按钮按下和释放事件处理程序
- python - 在 Docker 镜像中安装 argon2(安装 gcc 的问题)
- python - 如果翻译成 Javascript,我可以在 Google 表格中运行这个程序吗?
- javascript - Javascript if else 大于范围滑块
- mysql - phpmyadmin 错误:#1062 - 所有数据库上的键 'PRIMARY' 的重复条目 ''
- java - 获取所有 JAR 文件中所有类中带有注释 @Test 的所有方法
- java - 将具有多项式的c ++ crc16计算转换为android java