akuan10
akuan10

Reputation: 141

"How to fix 'attempting click action: waiting for element to be visible' error when clicking multiple boxes on a webpage using Playwright?"

I have a website, let's say "exampleA.com"

There are 12 clickable boxes on it, and clicking each box will take me to a different page. For example, clicking box1 will take me to page1.com, clicking box2 will take me to page2.com. I want to click every box on this page.

I am currently facing an issue where I get the following error

playwright._impl._api_types.Error: Element is not attached to the DOM.
attempting click action: waiting for element to be visible, enabled and stable

while running the following code:

boxes = page.query_selector_all(".something")
box1.click()
page.go_back()
box2.click()
page.go_back()

I have tried adding the following in between the code:

page.wait_for_load_state("networkidle")
page.wait_for_timeout(5000)

But the error still persists. How can I fix this bug?

Upvotes: 2

Views: 7572

Answers (2)

František
František

Reputation: 1

The error occurs because once you navigate away from the page, the DOM elements you previously selected (using query_selector_all) become stale. When you call page.go_back(), the original references to the boxes are no longer attached to the DOM, which causes the "Element is not attached to the DOM" error when you try to click them again.

To fix this, you need to re-select the element after each navigation. Instead of storing the elements once and reusing them, use Playwright’s locator API to fetch a fresh reference for each click.

You can do it in the loop, something like this:

box_locator = page.locator(".something")
box_count = box_locator.count()

for i in range(box_count):
    current_box = page.locator(".something").nth(i)
    
    current_box.click()
    page.wait_for_load_state("networkidle")
    
    page.go_back()
    page.wait_for_load_state("networkidle")

Upvotes: 0

Nguyễn Triệu Vĩ
Nguyễn Triệu Vĩ

Reputation: 49

Let try this:

page.locator(".something").first.wait_for(state="attached", timeout=5000)

Playwright: https://playwright.dev/python/docs/api/class-locator#locator-wait-for

Upvotes: 0

Related Questions