[日常] Go语言圣经--并发的web爬虫
2023-02-18 15:47:10 时间
两种:
crawler.go
package main import ( "fmt" "links" //"log" "os" ) func main() { worklist := make(chan []string) // Start with the command-line arguments. go func() { worklist <- os.Args[1:] }() // Crawl the web concurrently. seen := make(map[string]bool) for list := range worklist { for _, link := range list { if !seen[link] { seen[link] = true go func(link string) { worklist <- crawl(link) }(link) } } } } var tokens = make(chan struct{}, 20) //从一个url页面中提取出所有的url func crawl(url string) []string { fmt.Println(url) tokens <- struct{}{} list, err := links.Extract(url) <-tokens if err != nil { //log.Print(err) } return list }
crawler2.go
package main import ( "fmt" "links" //"log" "os" "strings" ) func main() { worklist := make(chan []string) unseenLinks := make(chan string) // Start with the command-line arguments. go func() { worklist <- os.Args[1:] }() // Create 20 crawler goroutines to fetch each unseen link. for i := 0; i < 20; i++ { go func() { for link := range unseenLinks { //if strings.HasPrefix(link, "http://www.lypeng.com") { foundLinks := crawl(link) go func() { worklist <- foundLinks }() //} } }() } // The main goroutine de-duplicates worklist items // and sends the unseen ones to the crawlers. seen := make(map[string]bool) for list := range worklist { for _, link := range list { if !seen[link] { seen[link] = true unseenLinks <- link } } } } //从一个url页面中提取出所有的url func crawl(url string) []string { fmt.Println(url) list, err := links.Extract(url) if err != nil { //log.Print(err) } return list }
相关文章
- 深入Git —— 从底层对象到常用命令速刷手册
- Java基础系列(25)- break、continue、goto
- 云图说|将源端MongoDB业务搬迁至华为云DDS的几种方式
- 【Google Cloud技术咨询】「Contact Center AI」引领我们走向高度智能客服的时代
- 【Git技术专题】如何使用git中的tag进行版本开发控制?
- Golang做一个IM即时通信系统
- 为什么Go的协程调度很快?
- 读猿码系列——1. gRPC+Etcd3的服务发现&负载均衡
- 读猿码系列——3. 从filebeat和go-stash深入日志收集及处理(filebeat篇)
- 读猿码系列——4. 从filebeat和go-stash深入日志收集及处理(go-stash篇)
- 读猿码系列——5.解析Golang常用定时任务库gron和cron
- 读猿码系列——6.Golang中用幂等思路解决缓存击穿的方案:singleflight
- Power BI 按钮:自定义图标
- Power BI x EasyShu:Top商品门店分布地图可视化
- Power BI 按钮:自定义动画
- 什么魔力要你升级到 MONGODB 6.0 (译)
- 1分钟快速生成可视化图:Power BI
- MONGODB 的存储引擎更快,更高,更强的秘诀 --译
- 2022GoLand激活码(2022GoLand最新激活码)2022GoLand激活码
- RSS Can:使用 Golang 实现更好的 RSS Hub 服务(一)