• 请不要在回答技术问题时复制粘贴 AI 生成的内容
zbl430
V2EX  ›  程序员

用 go 语言使用 goquery 爬去糗事百科热点笑话爬虫

  •  
  •   zbl430 · Sep 5, 2017 · 5783 views
    This topic created in 3205 days ago, the information mentioned may be changed or developed.

    这里直接贴代码

    package main
    
    import (
    	"fmt"
    	"github.com/PuerkitoBio/goquery"
    	"log"
    	"strings"
    )
    
    type HotsContent struct {
    	num     int
    	content string
    	comment string
    	url     string
    }
    
    
    func main() {
    	fmt.Println("开始爬取糗事百科热点笑话...")
    	js, err := goquery.NewDocument("https://www.qiushibaike.com/hot/")
    	if err != nil {
    		log.Fatal(err)
    	}
    	js.Find("#content-left .article").Each(func(i int, contentSelection *goquery.Selection) {
    		//先判断是否有图片
    		img, _ := contentSelection.Find(".thumb a").Attr("href")
    		if len(img) == 0 {
    			hotsArt := HotsContent{}
    			content := contentSelection.Find(".content span").Text()
    			url, _ := contentSelection.Find(".contentHerf").Attr("href")
    			comment_name := contentSelection.Find(".cmtMain .cmt-name").Text()
    			comment_cont := contentSelection.Find(".cmtMain .main-text").Text()
    			hotsArt.num = i + 1
    			hotsArt.url = "https://www.qiushibaike.com" + url
    			hotsArt.content = strings.Replace(content, "\n", "", -1)
    			hotsArt.comment = strings.Replace(comment_name+comment_cont, "\n", "", -1)
    			fmt.Println("第", hotsArt.num, "个笑话:")
    			fmt.Println("\t", hotsArt.content)
    			fmt.Println("\t 最热评论:" + hotsArt.comment)
    			fmt.Println("\t 地址", hotsArt.url)
    			fmt.Println("======================================================")
    		}
    	})
    }
    

    谢绝吐槽,写着练手玩玩的

    10 replies    2017-09-06 09:32:12 +08:00
    jjianwen68
        1
    jjianwen68  
       Sep 5, 2017
    几年前用过 goquery,挺好用
    zbl430
        2
    zbl430  
    OP
       Sep 5, 2017
    @jjianwen68 还可以
    qlbr
        3
    qlbr  
       Sep 5, 2017
    第一次见到活的 go 语言, 原来是酱紫的
    pathletboy
        4
    pathletboy  
       Sep 5, 2017
    你已经留了一个坑,结构体字段名首字母最好大写,避免将来踩坑。
    zbl430
        5
    zbl430  
    OP
       Sep 5, 2017
    @pathletboy 有道理,记住了
    yigemeirenyongde
        6
    yigemeirenyongde  
       Sep 5, 2017
    还在入门 go,前端转 go
    lixuda
        7
    lixuda  
       Sep 5, 2017
    感觉 go 越来越牛
    polaris1119
        8
    polaris1119  
       Sep 5, 2017
    go 发展还是挺猛的
    Akkuman
        9
    Akkuman  
       Sep 5, 2017
    go 写了几个网站,还行
    zbl430
        10
    zbl430  
    OP
       Sep 6, 2017
    @Akkuman 厉害
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3263 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 56ms · UTC 13:04 · PVG 21:04 · LAX 06:04 · JFK 09:04
    ♥ Do have faith in what you're doing.