這篇文章將為大家詳細(xì)講解有關(guān)如何使用Go秒爬博客園100頁(yè)新聞,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
10年積累的成都做網(wǎng)站、網(wǎng)站設(shè)計(jì)經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站制作后付款的網(wǎng)站建設(shè)流程,更有呼圖壁免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
利用go語(yǔ)言的協(xié)程并發(fā)優(yōu)勢(shì)爬取網(wǎng)頁(yè)速度相當(dāng)之快,博客園100頁(yè)新聞標(biāo)題只需一秒即可全部爬取
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) } }
關(guān)于“如何使用Go秒爬博客園100頁(yè)新聞”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。