go-colly 库能做什么?
What can the go-colly library do?
go-colly库能否抓取所有HTML标签和div标签下的文本内容?如果是这样,如何?我可以在 div 标签下获取所有文本。像这样:
c.OnHTML("body .post-topic-main .post-topic-des", func(e *colly.HTMLElement) {
text = strings.TrimSpace(e.Text)
})
但我不知道如何在 div 标签下获取 HTML 标签。
如果您要查找 innerHTML
,可以通过 DOM
并使用 Html
方法 (e.DOM.Html()
) 访问它。
c.OnHTML("body .post-topic-main .post-topic-des", func(e *colly.HTMLElement) {
html, _ := e.DOM.Html()
log.Println(html)
})
如果您在 founded 元素下寻找特殊标签,ForEach
可用于此目的。第一个参数是选择器,第二个参数是回调函数。回调函数将迭代每个与选择器匹配并且也是 e
元素成员的元素。
更多信息:https://pkg.go.dev/github.com/gocolly/colly@v1.2.0#HTMLElement.ForEach
c.OnHTML("body .post-topic-main .post-topic-des", func(e *colly.HTMLElement) {
text := strings.TrimSpace(e.Text)
log.Println(text)
e.ForEach("div", func(_ int, el *colly.HTMLElement) {
text := strings.TrimSpace(e.Text)
log.Println(text)
})
})
go-colly库能否抓取所有HTML标签和div标签下的文本内容?如果是这样,如何?我可以在 div 标签下获取所有文本。像这样:
c.OnHTML("body .post-topic-main .post-topic-des", func(e *colly.HTMLElement) {
text = strings.TrimSpace(e.Text)
})
但我不知道如何在 div 标签下获取 HTML 标签。
如果您要查找 innerHTML
,可以通过 DOM
并使用 Html
方法 (e.DOM.Html()
) 访问它。
c.OnHTML("body .post-topic-main .post-topic-des", func(e *colly.HTMLElement) {
html, _ := e.DOM.Html()
log.Println(html)
})
如果您在 founded 元素下寻找特殊标签,ForEach
可用于此目的。第一个参数是选择器,第二个参数是回调函数。回调函数将迭代每个与选择器匹配并且也是 e
元素成员的元素。
更多信息:https://pkg.go.dev/github.com/gocolly/colly@v1.2.0#HTMLElement.ForEach
c.OnHTML("body .post-topic-main .post-topic-des", func(e *colly.HTMLElement) {
text := strings.TrimSpace(e.Text)
log.Println(text)
e.ForEach("div", func(_ int, el *colly.HTMLElement) {
text := strings.TrimSpace(e.Text)
log.Println(text)
})
})