我正在尝试使用 colly 让特定的表循环遍历其内容,但该表未被识别,这是我到目前为止所拥有的。
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.jquery-tablesorter > tbody > tr", func(_ int, elem *colly.HTMLElement) { fmt.Println(elem.ChildAttr("a[href]", "href")) links = append(links, elem.ChildAttr("a[href]", "href")) }) }) 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.") }
我需要循环思考表中的所有 tr 元素。
事实证明,类的名称实际上是 wikitable.sortable
,即使在 chrome 控制台中显示为 wikitable sortable jquery-tablesorter
。我不知道为什么名称如此不同,但它解决了我的问题。