duanjing4667 2015-01-05 09:09
浏览 283
已采纳

遍历* 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条回答 默认 最新

  • douyue1926 2015-01-05 11:35
    关注

    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())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图