首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Go中使用cron定期运行Colly web scraper

在Go中使用cron定期运行Colly web scraper
EN

Stack Overflow用户
提问于 2021-11-13 06:06:50
回答 1查看 51关注 0票数 0

我正在使用colly进行一些web抓取,但我想使用cron定期运行它。我确实尝试了一种基本的方法。

代码语言:javascript
复制
type scraper struct {
    coll *colly.Collector
    rc   *redis.Client
}

func newScraper(c *colly.Collector, rc *redis.Client) scraper {
    return scraper{coll: c, rc: rc}
}

func main() {
    rc := redis.NewClient(&redis.Options{
        Addr:     "localhost:3000",
        Password: "", // no password set
        DB:       0,  // use default DB
    })

    coll := colly.NewCollector()

    scrape := newScraper(coll, rc)

    c := cron.New()
    c.AddFunc("@every 10s", scrape.scrapePls)
    c.Start()

    sig := make(chan int)
    <-sig
}

func (sc scraper) scrapePls() {
    sc.coll.OnHTML(`body`, func(e *colly.HTMLElement) {
        //Extracting required content

        //Using Redis to store data
    })

    sc.coll.OnRequest(func(r *colly.Request) {
        log.Println("Visting", r.URL)
    })

    sc.coll.Visit("www.example.com")
}

它似乎不起作用,只打了一次电话,也不会定期打下一次电话。不确定我是不是错过了什么。还有其他可以采取的方法吗?

任何帮助都将不胜感激。

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2021-11-13 11:57:52

c.AddFunc返回一个您没有检查的error,请检查,以防泄漏更多信息。

您应该能够检查c.Entries()的返回,这将为您提供有关下次调用函数的信息。

如果您没有意识到,您不需要一个完整的库来完成定期执行函数。例如,您可以执行以下操作:

代码语言:javascript
复制
scrape := newScraper(coll, rc)

sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
ticker := time.NewTicker(10 * time.Second)

// Run the function initially, so we don't have to wait 10 seconds for the first run (optional).
scrapePls()
for {
    select {
    case <-ticker.C:
        // Ticker will send a message every 10 seconds
        scrapePls()

        // You can also start a go routine every time. If scrapePls takes more than the interval
        // to run this may lead to issues to due to an forever increasing number of goroutines.
        // go scrapePls()
        
    case <-sig
        return
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69951890

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档