colly 是 Go 实现的比较有名的一款爬虫框架,而且 Go 在高并发和分布式场景的优势也正是爬虫技术所需要的。它的主要特点是轻量、快速,设计非常优雅,并且分布式的支持也非常简单,易于扩展。
使用
go get -u github.com/gocolly/colly
第一步,导入colly
import "github.com/gocolly/colly"
第二步,创建采集器
c := colly.NewCollector(
colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"),
colly.MaxDepth(1),
colly.Debugger(&debug.LogDebugger{}))
第三步,监听回调函数,获取需要的内容
// 诗词列表
c.OnHTML("div[class='right'] > div[class='sons'] > div[class='cont']", func(e *colly.HTMLElement) {
//
e.ForEach("a", func(i int, item *colly.HTMLElement) {
// 爬虫协程
//href := item.ChildAttr("a", "href")
attr := item.Attr("href")
text := item.Text
m := make(map[string]string, 10)
m["title"] = text
m["href"] = attr
// 把连接放进通道内
chanPoetry <- m
})
})
第四步,访问网址
s.Visit(href)
第五步,把爬取的文件写进文件里
for key := range chanPoetryContent {
// 获取链接
href := baseUrl + key["href"]
// 文件名称
fileName := key["title"]
dirName := key["text"]
s := colly.NewCollector(colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"), colly.MaxDepth(1), colly.Debugger(&debug.LogDebugger{}))
s.OnHTML("div[class='left'] ", func(e *colly.HTMLElement) {
name := e.ChildText("div[class='sons'][id='sonsyuanwen'] > div[class='cont'] > h1")
author := e.ChildText("div[class='sons'][id='sonsyuanwen'] > div[class='cont'] > p[class='source'] > a")
text := e.ChildText("div[class='sons'][id='sonsyuanwen'] > div[class='cont'] > div[class='contson']")
content := name + "\r\n" + author
text = strings.Replace(text, "。", "。\r\n", 99999)
text = strings.Replace(text, ";", ";\r\n", 99999)
text = strings.Replace(text, ")", ")\r\n", 99999)
path := mainDir + "/诗词/" + dirName
if len(fileName) > 0 {
path = path + "/" + fileName
}
if len(name) == 0 {
return
} else {
// 创建目录
makeDir(path)
file, _ := os.OpenFile(path+"/"+name+".txt", os.O_CREATE|os.O_WRONLY, 0644)
file.WriteString(content + "\r\n")
file.WriteString(text + "\r\n")
// 关闭资源
file.Close()
}
})
s.Visit(href)
}
waitGroup.Done()
版权声明:本文为u012868901原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。