登录
首页 >  Golang >  Go问答

使用 Go Colly 处理网页中的多个元素

来源:stackoverflow

时间:2024-03-02 17:09:24 310浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《使用 Go Colly 处理网页中的多个元素》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我有一个结构如下:

type post struct{
     id int64
     title string
     content string
}

我用go colly curl一个网页来接收数据,我有两个onhtml方法如下:

func main() {
    c := colly.newcollector()

    c.onhtml("p", func(e *colly.htmlelement) {
        post := post{
           content: e.text
        }
        db.create(&post)
    })
    c.onhtml("h", func(e *colly.htmlelement) {
        post := post{
           title: e.text
        }
        db.create(&post)        
    })

    c.visit("http://go-colly.org/")
}

上面的代码运行良好,但这会在数据库中创建两行,如下所示:

+--------------+---------------+---------------+
|      id      |     title     |    content    |
+--------------+---------------+---------------+
|       1      |      hello    |      null     |
+--------------+---------------+---------------+
|       2      |      null     | mycontent ... |
+--------------+---------------+---------------+

我想创建它:

+--------------+---------------+---------------+
|      id      |     title     |    content    |
+--------------+---------------+---------------+
|       1      |      Hello    | Mycontent ... |
+--------------+---------------+---------------+

如何在 go colly 中获取两个元素并保存在一行中?


解决方案


您应该阅读以下示例:http://go-colly.org/docs/examples/coursera_courses/,位于 detailCollector.OnHTML("div[id=rendered-content]", func(e *colly.HTMLElement) {

该示例在封装整个内容的元素(此处为 div)上设置了 onHTML,因此对于您来说,您需要找到封装包含标题 + 内容的每个帖子的元素,然后执行 e.ForEach 来解析每一篇文章。

编辑:http://go-colly.org/docs/examples/factbase/ 也是您的用例的一个很好的例子。获取正文,然后用演讲者和文本解析每个主题。

清楚了吗?

理论要掌握,实操不能落!以上关于《使用 Go Colly 处理网页中的多个元素》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>