'Golang Chromedp reload current page until find some html object
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?
Solution 1:[1]
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]))
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Zeke Lu |