You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用chromedp从多个动态命名的textarea中选中指定文本框

使用chromedp定位并修改动态类名的第一个textarea值

问题场景

页面包含5个name/id/类名均为动态生成且完全一致的textarea,无法通过常规属性选择器定位,需选中第一个并修改其值。

解决方案

利用你找到的CSS选择器.elementor-repeater-fields:nth-child(2) textarea,结合chromedp的API实现元素定位与值修改,示例代码如下:

package main

import (
	"context"
	"github.com/chromedp/chromedp"
)

func main() {
	// 初始化chromedp上下文
	ctx, cancel := chromedp.NewContext(context.Background())
	defer cancel()

	// 执行页面操作
	err := chromedp.Run(ctx,
		// 导航到目标页面
		chromedp.Navigate("替换为你的目标页面URL"),
		// 等待目标textarea加载可见,避免动态渲染导致元素未就绪
		chromedp.WaitVisible(`.elementor-repeater-fields:nth-child(2) textarea`, chromedp.ByQuery),
		// 设置textarea的内容
		chromedp.SetValue(`.elementor-repeater-fields:nth-child(2) textarea`, "需要设置的内容", chromedp.ByQuery),
	)
	if err != nil {
		panic(err)
	}
}

验证与调整

如果需要确认是否定位到正确的元素,可以在设置值之前添加文本获取逻辑,验证元素内容:

var currentContent string
chromedp.Text(`.elementor-repeater-fields:nth-child(2) textarea`, &currentContent, chromedp.ByQuery),
// 打印当前内容确认
// fmt.Println(currentContent)

注:确保你的CSS选择器.elementor-repeater-fields:nth-child(2) textarea确实指向目标第一个textarea,若页面结构有变化,需调整nth-child的索引值。

内容的提问来源于stack exchange,提问作者Angelo van Cleef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:15:18