Home > Backend Development > Golang > chromedp How to select specific textarea from multiple textareas with dynamic names

chromedp How to select specific textarea from multiple textareas with dynamic names

WBOY
Release: 2024-02-05 22:42:12
forward
627 people have browsed it

chromedp 如何从多个具有动态名称的文本区域中选择特定文本区域

Question content

I have a page with multiple text areas consisting of dynamic names and the same class. This means I can't select them by id, name, class or type.

All I know is that out of the 5 textareas, I need the first one, and I want to change the value of that textarea.

Can anyone tell me how to do this using chromedp? Been trying for two days with no progress.

Find the answer:

const n = document.querySelector('.elementor-repeater-fields:nth-child(2) textarea'); console.log(n);


Correct answer


Use pseudo-class :first-child a> 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)
    }
}
Copy after login

The above is the detailed content of chromedp How to select specific textarea from multiple textareas with dynamic names. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template