英文:
Getting attribute value with Go Colly
问题
当使用c.OnHTML在"html"中工作时,如何获取#id-card-1 ID内href属性的值?
c.OnHTML("html", func(e *colly.HTMLElement) {
...
linkStr := "#id-card-1[href]" //???
log.Print(e.Attr(linkStr))
...
})
这是页面中的HTML片段:
英文:
When working with c.OnHTML in "html", how can I get the value of the href attribute inside the #id-card-1 ID?
c.OnHTML("html", func(e *colly.HTMLElement) {
...
linkStr := "#id-card-1[href]" //???
log.Print(e.Attr(linkStr))
...}
This is the piece of HTML in the page:
<a href="/some-link-here" target="_blank" id="id-card-1" class="card card--featured" data-item-card="11042036">
答案1
得分: 1
ChildAttr
函数可以用于此目的。
> ChildAttr
返回第一个匹配元素的属性的剥离文本内容。
https://pkg.go.dev/github.com/gocolly/colly#HTMLElement.ChildAttr
c.OnHTML("html", func(e *colly.HTMLElement) {
linkStr := "#id-card-1"
log.Println(e.ChildAttr(linkStr, "href"))
})
英文:
The ChildAttr
function can use for this purpose.
> ChildAttr returns the stripped text content of the first matching
> element's attribute.
https://pkg.go.dev/github.com/gocolly/colly#HTMLElement.ChildAttr
c.OnHTML("html", func(e *colly.HTMLElement) {
linkStr := "#id-card-1"
log.Println(e.ChildAttr(linkStr, "href"))
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论