欢迎来到代码驿站!

Golang

当前位置:首页 > 脚本语言 > Golang

Go秒爬博客园100页新闻

时间:2020-11-28 14:36:17|栏目:Golang|点击:

利用go语言的协程并发优势爬取网页速度相当之快,博客园100页新闻标题只需一秒即可全部爬取

package main

import (
 "bytes"
 "fmt"
 "github.com/PuerkitoBio/goquery"
 "log"
 "net/http"
 "runtime"
 "strconv"
 "sync"
)

func Scraper(page string) string {
 // Request the HTML page.
 ScrapeURL := "https://news.cnblogs.com/n/page/" + page
 client := &http.Client{}
 reqest, _ := http.NewRequest("GET", ScrapeURL, nil)
 reqest.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
 reqest.Header.Set("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3")
 //reqest.Header.Set("Accept-Encoding", "gzip,deflate,sdch")
 reqest.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
 reqest.Header.Set("Cache-Control", "max-age=0")
 reqest.Header.Set("Connection", "keep-alive")
 reqest.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36")
 res, err := client.Do(reqest)
 if err != nil {
  log.Fatal(err)
 }
 defer res.Body.Close()
 if res.StatusCode != 200 {
  log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
 }

 // Load the HTML document
 doc, err := goquery.NewDocumentFromReader(res.Body)
 if err != nil {
  log.Fatal(err)
 }

 // Find the review items
 var buffer bytes.Buffer
 buffer.WriteString("**********Scraped page " + page + "**********\n")
 doc.Find(".content .news_entry").Each(func(i int, s *goquery.Selection) {
  // For each item found, get the band and title
  title := s.Find("a").Text()
  url, _ := s.Find("a").Attr("href")
  buffer.WriteString("Review " + strconv.Itoa(i) + ": " + title + "\nhttps://news.cnblogs.com" + url + "\n")
 })
 return buffer.String()
}

func main() {
 runtime.GOMAXPROCS(runtime.NumCPU())
 ch := make(chan string, 100)
 wg := &sync.WaitGroup{}
 var page string
 for i := 1; i < 101; i++ {
  wg.Add(1)
  go func(i int) {
   page = strconv.Itoa(i)
   fmt.Printf("Scraping page %s...\n", page)
   ch <- Scraper(page)
   wg.Done()
  }(i)
 }
 wg.Wait()

 //print result
 for i := 0; i < 101; i++ {
  fmt.Println(<-ch)
 }
}

上一篇:浅谈Go Slice 高级实践

栏    目:Golang

下一篇:GO语言的IO方法实例小结

本文标题:Go秒爬博客园100页新闻

本文地址:http://www.codeinn.net/misctech/27263.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有