美文网首页
go爬虫框架-colly实战(二)--豆瓣top250爬取

go爬虫框架-colly实战(二)--豆瓣top250爬取

作者: 你就像只铁甲小宝 | 来源:发表于2019-12-25 12:01 被阅读0次

    原文连接:Hzy 博客

    1.今天就尝试用colly来爬取豆瓣Top 250!(大家都喜欢拿他来练手..)

    直接上代码了,上面有注释。

    package main
    
    import (
        "fmt"
        "github.com/PuerkitoBio/goquery"
        "github.com/gocolly/colly"
        "github.com/gocolly/colly/extensions"
        "regexp"
        "strings"
        "time"
    )
    
    func main() {
        t := time.Now()
        number := 1
        c := colly.NewCollector(func(c *colly.Collector) {
            extensions.RandomUserAgent(c) // 设置随机头
            c.Async=true
        },
            //过滤url,去除不是https://movie.douban.com/top250?start=0&filter= 的url
            colly.URLFilters(
                regexp.MustCompile("^(https://movie\\.douban\\.com/top250)\\?start=[0-9].*&filter="),
            ),
        ) // 创建收集器
        // 响应的格式为HTML,提取页面中的链接
        c.OnHTML("a[href]", func(e *colly.HTMLElement) {
            link := e.Attr("href")
            //fmt.Printf("find link: %s\n", e.Request.AbsoluteURL(link))
            c.Visit(e.Request.AbsoluteURL(link))
        })
        // 获取电影信息
        c.OnHTML("div.info", func(e *colly.HTMLElement) {
            e.DOM.Each(func(i int, selection *goquery.Selection) {
                movies := selection.Find("span.title").First().Text()
                director := strings.Join(strings.Fields(selection.Find("div.bd p").First().Text()), " ")
                quote := selection.Find("p.quote span.inq").Text()
                fmt.Printf("%d --> %s:%s %s\n", number, movies, director, quote)
                number += 1
            })
        })
        c.OnError(func(response *colly.Response, err error) {
            fmt.Println(err)
        })
        c.Visit("https://movie.douban.com/top250?start=0&filter=")
        c.Wait()
        fmt.Printf("花费时间:%s",time.Since(t))
    }
    
    
    colly-top250.png

    感觉用这个框架还是挺方便的,明天在来试试爬取一些需要登录的网站!

    相关文章

      网友评论

          本文标题:go爬虫框架-colly实战(二)--豆瓣top250爬取

          本文链接:https://www.haomeiwen.com/subject/yfhcoctx.html