英文:
Iterate over *goquery.Selection
问题
我刚几天前开始学习Go语言,所以请耐心等待。😊
我正在使用goquery
从网页中获取文本,就像这样:
package main
import (
"fmt"
"log"
"github.com/PuerkitoBio/goquery"
)
func ExampleScrape() {
doc, err := goquery.NewDocument("http://lifehacker.com")
if err != nil {
log.Fatal(err)
fmt.Println("失败")
} else {
fmt.Println("成功")
}
h1_text := doc.Find("h1").Text()
fmt.Println(h1_text)
}
func main() {
ExampleScrape()
}
这个代码运行得很好。但是我无法弄清楚如何将doc.Find("h1").Text()
的选择结果转换为数组或切片,以便我可以遍历它们(或者更好的是,找出goquery
是否有相应的函数)。我相信一定有办法做到这一点,对吗?
我尝试在func ExampleScrape
中这样做:
var x []string
doc.Find("h1").Each(func(i int, s *goquery.Selection) {
append(x, s.Text())
})
但是它不起作用,因为append
在嵌套/闭包函数中仅在该函数内部有效,它不会返回到func ExampleScrape
。然后我尝试了这个:
x := doc.Find("h1").Each(func(i int, s *goquery.Selection) {
return s.Text()
})
for _, i := range x {
fmt.Println(x)
}
但是*goquery.Selection
类型无法进行迭代。
有没有办法像这样遍历*goquery.Selection
呢?
顺便说一句,你们在这里真棒。我总是对在这里得到的答案感到惊讶。如果有人能解释一下如何做到这一点,提前谢谢你们。😊
英文:
I just started learning Go a couple days ago, so bear with me please.
I'm fetching text from a web page with goquery
. Like this:
package main
import (
"fmt"
"log"
"github.com/PuerkitoBio/goquery"
)
func ExampleScrape() {
doc, err := goquery.NewDocument("http://lifehacker.com")
if err != nil {
log.Fatal(err)
fmt.Println("fail")
} else {
fmt.Println("got it")
}
h1_text := doc.Find("h1").Text()
fmt.Println(h1_text)
}
func main() {
ExampleScrape()
}
This works great. What I can't figure out is how to turn the doc.Find("h1").Text()
selection into an array or slice so that I can iterate over them (or, even better, figuring out if goquery
has a function for this). I'm sure there's a way to do this, right?
I tried doing this (inside func ExampleScrape
):
var x []string
doc.Find("h1").Each(func(i int, s *goquery.Selection) {
append(x, s.Text())
})
but it didn't work because append
in the 'nested'/closure function remains local to that function--it doesn't get returned back to func ExampleScrape
. So then I tried this:
x := doc.Find("h1").Each(func(i int, s *goquery.Selection) {
return s.Text()
})
for _, i := range x {
fmt.Println(x)
}
but *goquery.Selection
types can't be ranged over.
Is there a way to iterate over *goquery.Selection
's like this?
You guys on here are awesome, by the way. I'm always blown away by the answers I get on here. If someone can explain how to do this, thanks a googolplex in advance.
答案1
得分: 3
我认为你的第一次尝试可能会成功,如果你正确使用了append
函数的话。
append(x, s.Text())
并不会改变x的值,而是返回一个新的切片。
所以你真正需要做的是:
x = append(x, s.Text())
英文:
I think your first attempt could work if you used append
properly.
append(x, s.Text())
does not change x, rather it returns a new slice.
so you really need to do:
x = append(x, s.Text())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论