Home > database >  ChromeDp how to select specific textarea from multiple with dynamic names
ChromeDp how to select specific textarea from multiple with dynamic names

Time:11-22

I have a page which has multiple textarea's which are made with dynamic names and identical classes. This means I cannot select them by id, name, class or type.

What I do know is that out of the 5 textarea's, I need the first one and I want to change the value of that one.

Can anyone tell me how I can do this with ChromeDp? been trying for two days without any progress.

CodePudding user response:

Use pseudo-class :first-child or :nth-child to select the target element. For example:

package main

import (
    "context"
    "fmt"
    "net/http"
    "net/http/httptest"
    "time"

    "github.com/chromedp/chromedp"
)

func main() {
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, `
<html>
  <body>
    <textarea></textarea>
    <textarea></textarea>
    <textarea></textarea>
  </body>
</html>
`)
    }))
    defer ts.Close()

    opts := append(chromedp.DefaultExecAllocatorOptions[:],
        chromedp.Flag("headless", false),
    )
    ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
    defer cancel()
    ctx, cancel = chromedp.NewContext(ctx)
    defer cancel()

    err := chromedp.Run(ctx,
        chromedp.Navigate(ts.URL),
        chromedp.Sleep(time.Second),
        chromedp.SetValue(`body>textarea:first-child`, "hello world!", chromedp.ByQuery),
        chromedp.Sleep(time.Second),
        chromedp.SetValue(`body>textarea:nth-child(2)`, "hello chromedp!", chromedp.ByQuery),
        chromedp.Sleep(3*time.Second),
    )
    if err != nil {
        panic(err)
    }
}
  • Related