0
chromedp.Navigate(tragetUrl),
chromedp.WaitVisible("#button"),
chromedp.Click("#button"),

Goal: if #button is not exist then reload the current page until button appear and click it

The #button appears at random times and depending on the target website.

Is any good suggestions to achieve above goal?

ChouChun
  • 5
  • 1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jan 17 '22 at 17:58

1 Answers1

0

The key is to use the option chromedp.AtLeast(0). See the demo below:

func ReloadUntilButtonAppears(ctx context.Context, targetURL string) error {
    var nodes []*cdp.Node
    for {
        if err := chromedp.Run(ctx,
            chromedp.Navigate(targetURL),
            // chromedp.AtLeast(0) makes the query return immediately
            // even if there are not nodes found.
            chromedp.Nodes("#button", &nodes, chromedp.ByQuery, chromedp.AtLeast(0)),
        ); err != nil {
            return err
        }
        if len(nodes) > 0 {
            return chromedp.Run(ctx, chromedp.MouseClickNode(nodes[0]))
        }
    }
}
Zeke Lu
  • 6,349
  • 1
  • 17
  • 23