【问题标题】:ChromeDp how to select specific textarea from multiple with dynamic namesChromeDp 如何从多个具有动态名称的文本区域中选择特定的文本区域
【发布时间】:2022-11-21 11:57:36
【问题描述】:

我有一个包含多个文本区域的页面,这些文本区域由动态名称和相同的类组成。这意味着我无法通过 ID、名称、类或类型来选择它们。

我所知道的是,在 5 个文本区域中,我需要第一个并且我想更改它的值。

谁能告诉我如何使用 ChromeDp 做到这一点?试了两天,没有任何进展。

【问题讨论】:

    标签: go chromedp


    【解决方案1】:

    使用伪类:first-child:nth-child选择目标元素。例如:

    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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 2020-03-07
      • 2011-08-13
      • 2017-02-11
      • 1970-01-01
      • 2018-11-04
      • 2023-03-19
      相关资源
      最近更新 更多