go - 如何使用go colly在页面上获取多个元素

标签 go web-scraping

我有一个结构如下:

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 ... |
+--------------+---------------+---------------+

如何获取两个元素并保存到goly中的一行中?

最佳答案

您应该阅读以下示例: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/还是您的用例的一个很好的例子。捕获 body ,然后用演讲者和文字分析每个主题。

明白了吗?

关于go - 如何使用go colly在页面上获取多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60596820/

相关文章:

go - 如何仅使用一种方法删除不同类型的 slice

json - golang json迭代不支持索引

python-3.x - 使用 python 3.6 和 beautifulsoup 进行网络抓取 - 获取无效的 URL

Python 网页抓取 : I have a website with pick list. 以及如何提取这些列表中的文本

python - Scrapy 元素声明中的 IF 语句

algorithm - 算法。添加两个n位二进制数。这个问题的循环不变性是什么?

node.js - NodeJS vs Golang for REST API 并用它实现后端

HTTP-POST 文件多部分

python - 从无限滚动的网页获取所有文章链接?

python - 如何从交互式代码中抓取数据