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

如何用Go Colly定位目标表格并遍历其中的<tr>元素?

问题解决思路

你的代码无法识别目标表格主要有两个核心问题:

  • CSS选择器里的&gt;是HTML转义字符,Colly的选择器解析逻辑无法识别该转义符号,必须替换为原生的>。
  • jquery-tablesorter是页面加载后由JavaScript动态添加的类名,Colly默认不执行JS,选择器中包含这个类会导致匹配不到实际存在的表格。
修正后的代码
package main

import (
    "fmt"
    
    "github.com/gocolly/colly"
)

func main() {
    c := colly.NewCollector(
        colly.AllowedDomains("wikipedia.org", "en.wikipedia.org"),
    )
    
    links := make([]string, 0)

    c.OnHTML("div.mw-parser-output", func(e *colly.HTMLElement) {
        // 移除动态添加的类名,替换转义符号为原生层级选择符
        e.ForEach("table.wikitable.sortable > tbody > tr", func(_ int, elem *colly.HTMLElement) {
            link := elem.ChildAttr("a[href]", "href")
            if link != "" {
                fmt.Println(link)
                links = append(links, link)
            }
        })
    })
    
    c.OnRequest(func(r *colly.Request) {
        fmt.Println("Visiting", r.URL.String())
    })

    c.Visit("https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population")
    fmt.Println("Found urls for", len(links), "countries.")
}
额外优化提示

如果需要跳过表格的表头行,可以在遍历回调中添加索引判断:

e.ForEach("table.wikitable.sortable > tbody > tr", func(i int, elem *colly.HTMLElement) {
    // 跳过索引为0的表头行
    if i == 0 {
        return
    }
    link := elem.ChildAttr("a[href]", "href")
    if link != "" {
        fmt.Println(link)
        links = append(links, link)
    }
})

内容的提问来源于stack exchange,提问作者Lynx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 18:15:38