使用 puppeteer 进行基于哈希的导航

Hash-based navigation with puppeteer

我正在尝试导航到 url,它在返回 Error: Navigation Timeout Exceeded: 30000ms exceeded

的 url 中包含 #
it('should go to new link', async function(){
    await page.goto('https://example.com/#/abc', {waitUntil: 'networkidle2'})
    await page.waitForNavigation()
    await page.waitFor(15000);
})

原始代码需要一个值为 #/abc

的标签的路径
    await page.waitForSelector('a tag selector')
    await page.click('a tag selector')
    await page.waitForNavigation()
    await page.waitFor(5000);
    await page.screenshot({ path: 'abc.png' })

运行 命令为 mocha --timeout 75000

的测试文件

package.json

"devDependencies": {
    "chai": "^4.1.2",
    "karma": "^2.0.3",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-mocha": "^1.3.0",
    "karma-requirejs": "^1.1.0",
    "mocha": "^5.2.0"
},
"dependencies": {
  "puppeteer": "^0.12.0",
  "requirejs": "^2.3.5"

}

已将代码更新为

await page.goto('https://example.com/#/abc', {waitUntil: 'load'})
await page.waitForSelector('selector on desired page');
await page.waitFor(5000);
await page.screenshot({ path: 'abc.png' })

并添加了 headless: false,我可以看到它确实进入页面等待了一段时间但仍然抛出错误 Error: Navigation Timeout Exceeded: 30000ms exceeded

goto自动等待导航。您的 waitForNavigation 期待它发出另一个导航请求。您也无需等待 25 秒即可完成此操作。

然而,对于这样的 ajax 站点,IMO,您应该等待一些选择器,该选择器仅在页面完全加载时才加载。

您也可以传递一个超时参数来增加超时时间,看看是否可行。

以下就够了。

it('should go to new link', async function(){
    await page.goto('https://example.com/#/abc', {waitUntil: 'networkidle2', timeout: 60000 })
    await page.waitFor('#SomeSelectorThatWeWaitFor')
})

调试此问题的最佳方法是仔细查看目标页面的行为。