Golang中Chromedp选择器的使用与配置指南
Golang中Chromedp选择器的使用与配置指南
能否解释一下这些 Chromedp 选择器选项?
//后面有一个星号 - 这代表什么意思?- 在
h2部分,contains中 - 开括号后面加一个点符号是什么意思?
chromedp.WaitNotPresent(`//*[@id="js-pjax-container"]//h2[contains(., 'Search more than')]`),
2 回复
这并不是Go语言特有的,传递的字符串看起来有点像XPath选择器,但这只是猜测。也许这足够你进行搜索了。
更多关于Golang中Chromedp选择器的使用与配置指南的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
这是一个关于Chromedp选择器语法的专业解释:
1. // 后面的星号含义
//* 中的星号是XPath通配符,表示匹配任意元素节点。具体来说:
//表示从文档任意位置开始搜索*表示匹配任何元素标签(div、span、h1等)
示例:
// 匹配任意id为"js-pjax-container"的元素
chromedp.WaitVisible(`//*[@id="js-pjax-container"]`)
// 对比:只匹配div元素中id为"js-pjax-container"的
chromedp.WaitVisible(`//div[@id="js-pjax-container"]`)
2. contains(., 'text') 中的点号含义
在XPath的contains()函数中,点号.代表当前节点的文本内容。具体解释:
contains(., 'Search more than')检查当前h2元素的文本内容是否包含’Search more than’- 点号是XPath的简写,等价于
text()
示例:
// 匹配文本包含"Search more than"的h2元素
chromedp.WaitNotPresent(`//h2[contains(., 'Search more than')]`)
// 等价写法
chromedp.WaitNotPresent(`//h2[contains(text(), 'Search more than')]`)
// 实际应用:等待特定文本消失
chromedp.Run(ctx,
chromedp.Navigate("https://example.com"),
chromedp.WaitNotPresent(`//h1[contains(., 'Loading')]`),
)
完整示例代码
package main
import (
"context"
"log"
"time"
"github.com/chromedp/chromedp"
)
func main() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ctx, cancel = context.WithTimeout(ctx, 30*time.Second)
defer cancel()
err := chromedp.Run(ctx,
chromedp.Navigate("https://github.com/search"),
// 等待任意包含特定id的元素出现
chromedp.WaitVisible(`//*[@id="js-pjax-container"]`),
// 等待包含特定文本的h2元素消失
chromedp.WaitNotPresent(`//*[@id="js-pjax-container"]//h2[contains(., 'Search more than')]`),
// 后续操作
chromedp.Value(`//input[@name="q"]`, &searchValue),
)
if err != nil {
log.Fatal(err)
}
}
这个选择器的完整含义是:等待id为"js-pjax-container"的元素内,所有文本包含’Search more than’的h2元素从DOM中消失。

