英文:
chromedp how to select specific textarea from multiple with dynamic names
问题
我有一个页面,其中有多个使用动态名称和相同类的文本区域。这意味着我无法通过id、名称、类或类型来选择它们。
我知道的是,在这5个文本区域中,我需要第一个,并且我想要更改该文本区域的值。
有人可以告诉我如何使用chromedp来做到这一点吗?我已经尝试了两天,没有任何进展。
找到了答案:
const n = document.querySelector('.elementor-repeater-fields:nth-child(2) textarea'); console.log(n);
英文:
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.
Found the answer:
const n = document.querySelector('.elementor-repeater-fields:nth-child(2) textarea'); console.log(n);
答案1
得分: 0
使用伪类: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)
	}
}
英文:
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)
	}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论