首页 > 解决方案 > 使用 Go-Colly 抓取时删除空行

问题描述

我从 Go 开始,并从 Colly 开始。有人可以帮我从输出中删除空行吗?这是我的代码:

package main

import (
    "fmt"

    "github.com/gocolly/colly"
)

func main() {
    c := colly.NewCollector()
    c.OnHTML("table > tbody", func(e *colly.HTMLElement) {
        fmt.Println(e.Text)
    })
    c.Visit("https://www.olx.pl/elektronika/gdynia/")
}

我试过这个:golang regexp remove all blank lines 和这个:Golang idiomatic way to remove a blank line from a multi-line string,可能是错误的方式,或者我错过了其他东西。

标签: go

解决方案


我认为您可以尝试标准化空间。

func StandardizeSpaces(s string) string {
    return strings.Join(strings.Fields(s), " ")
}

func main() {
    c := colly.NewCollector()
    c.OnHTML("table > tbody", func(e *colly.HTMLElement) {
        fmt.Println(StandardizeSpaces(e.Text))
    })
    c.Visit("https://www.olx.pl/elektronika/gdynia/")
}

推荐阅读