1、Quick Start
只需三步,你就可以部署一个爬取 gocn 网站的所有新闻的爬虫
第一步,你需要去 github 上生成一个自己的 token Settings ——> Developer settings ——> Personal access tokens ——> Generate new token
然后,配置自己的环境变量 export GITHUB_TOKEN=(第一步生成的 token),或者将代码中全局 Token 修改为自己 token
var Token = GetValueFromEnv(“GITHUB_TOKEN”)
第二步,需要在本地安装 redis,并且启动程序之前需要先启动本地 redis,端口使用默认端口 6379,因为程序默认使用 redis 进行去重。redis 的安装 可以参考 redis安装
第三步,git clone 代码仓库,并且在后台进程中运行爬虫,每 6 个小时爬取当天新闻并进行 github 推送。
git clone https://github.com/lubanproj/crawl.git
cd crawl
go build -v
./crawl &
2、特性
- 支持每天定时爬取
- 支持分页爬取
- 支持数据去重
- 支持 github 推送
3、展示效果
详情效果可见:go_read
4、源码分析
(1)爬取网站
// Crawl all gocn topics
func Crawl(url string) {
pattern := `/topics/\d+`
collector := colly.NewCollector()
collector.OnHTML("a[title]", func(e *colly.HTMLElement) {
// regex match topic
path := e.Attr("href")
topic, ok := regexMatch(path, pattern)
if ok {
e.Request.Visit(fmt.Sprintf("https://gocn.vip%s",topic))