要查找子元素的子元素,可以使用 Colly 提供的方法 'ChildText(selector string)''ChildAttr(selector string, attribute string)'

例如,假设有一个 HTML 元素如下:

<div class="parent">
  <div class="child">
    <span class="grandchild">Grandchild Text</span>
  </div>
</div>

想要获取 'span' 元素的文本内容,可以使用以下代码:

c.OnHTML(".parent", func(e *colly.HTMLElement) {
    grandchildText := e.ChildText(".child .grandchild")
    fmt.Println(grandchildText) // 输出 'Grandchild Text'
})

如果想要获取 'span' 元素的某个属性值,例如 'data-id',可以使用以下代码:

c.OnHTML(".parent", func(e *colly.HTMLElement) {
    grandchildID := e.ChildAttr(".child .grandchild", "data-id")
    fmt.Println(grandchildID) // 输出 '123'
})
Go Colly: 如何查找子元素的子元素

原文地址: https://www.cveoy.top/t/topic/obA9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录