gogoquery

A little bit lost with goQuery selection


I'm new to Go and I'm trying to learn it by making a repost bot. Anyway, I'm having a problem that I don't know how to solve exactly.

I have the following Struct:

type Post struct {
    Title string
    Url   string
}

And I'm trying to get these values using goQuery, like this:

var title = doc.Find(".title.title.may-blank").Each(func(i int, s *goquery.Selection) {
        fmt.Println("Title:", s.Text())
})

But when I try to set the value to the Post struct, I get this error:

cannot use title (type *goQuery.Selection) as type string in field value. 

Ok, that makes sense, but how can I cast it to string? I've tried s.Text() but it doesn't works. I thought about making a function that returns a string, but I'm not sure if this would work.

I'll appreciate if someone can help me, thanks in advance!


Solution

  • The issue is that .Each returns the original *goquery.Selection so that you can chain calls. If you need to get the string value, you just assign it directly, like this:

    var title string
    doc.Find(".title.title.may-blank").Each(func(i int, s *goquery.Selection) {
        title = s.Text()
    })