使用剧作家导航后元素不可见

Element not visible after navigating using playwright

我正在使用 playwright 来实现我的浏览器自动化。

我单击一个超链接,将我带到 Google.com,我想验证导航后是否存在“Google 搜索”按钮。 这是我的代码。

const textToClick = "Visit Google"
const textToVerify = "Google Search"
const elements = await page.$$(`text=${textToClick}`)
await element[0].click()
const elements = await page.$$(`text=${textToVerify}`)
const elementLength = elements.length
console.log("Element Length::",elementLength, ":: TexToFind::",textToVerify)

当我运行用摩卡测试时,找不到“Google搜索”按钮。

但是当我 运行 通过节点主入口文件下的 visual studio 调试器使用相同的代码时(main.js);我能够找到“Google 搜索”按钮。

这是来自 mocha 测试的 playwright 调试器的输出 运行:

pw:api => page.goto started +0ms
pw:api navigating to "file:///C:/devel/devspace/js/myAutomation/test/src/sampleApp.html", waiting until "load" [] +3ms
pw:api navigated to "file:///C:/devel/devspace/js/myAutomation/test/src/sampleApp.html" [] +348ms
pw:api "domcontentloaded" event fired [] +7ms
pw:api "load" event fired [] +276ms
pw:api <= page.goto succeeded +6ms
pw:api => elementHandle.click started +364ms
pw:api attempting elementHandle.click action [] +2ms
pw:api waiting for element to be visible, enabled and not moving [] +2ms
pw:api element is visible, enabled and does not move [] +479ms
pw:api scrolling into view if needed [] +1ms
pw:api done scrolling [] +63ms
pw:api checking that element receives pointer events at (358.64,558.1) [] +66ms
pw:api element does receive pointer events [] +188ms
pw:api performing elementHandle.click action [] +2ms
pw:api elementHandle.click action done [] +83ms
pw:api waiting for scheduled navigations to finish [] +3ms
pw:api navigated to "https://www.google.com/" [] +293ms
pw:api navigations have finished [] +46ms
pw:api <= elementHandle.click succeeded +2ms
sleeping
sleeping finished
element Length:: 0 :: TexToFind:: Google Search
1) Test Click Functionality on Hyperlink

您会注意到元素长度为零,表示未找到“Google 搜索”按钮

什么是 mocha 测试导致元素不可搜索,或者是否有一些与超链接相关的基本问题需要在点击超链接将您带到新网页后验证元素时处理?

点击第一个 link 将导致导航。所以你需要等待页面导航到Google。你可以这样做:

await Promise.all([elements[0].click(), page.waitForNavigation()]);