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

2017 年 9 月 5 日
 zbl430

这里直接贴代码

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("======================================================")
		}
	})
}

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

5952 次点击
所在节点    程序员
10 条回复
jjianwen68
2017 年 9 月 5 日
几年前用过 goquery,挺好用
zbl430
2017 年 9 月 5 日
@jjianwen68 还可以
qlbr
2017 年 9 月 5 日
第一次见到活的 go 语言, 原来是酱紫的
pathletboy
2017 年 9 月 5 日
你已经留了一个坑,结构体字段名首字母最好大写,避免将来踩坑。
zbl430
2017 年 9 月 5 日
@pathletboy 有道理,记住了
yigemeirenyongde
2017 年 9 月 5 日
还在入门 go,前端转 go
lixuda
2017 年 9 月 5 日
感觉 go 越来越牛
polaris1119
2017 年 9 月 5 日
go 发展还是挺猛的
Akkuman
2017 年 9 月 5 日
go 写了几个网站,还行
zbl430
2017 年 9 月 6 日
@Akkuman 厉害

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://v2ex.ih06.com/t/388217

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX