Go 百度貼吧、捧腹段子并發(fā)爬蟲

爬蟲設(shè)計

爬蟲設(shè)計步驟:

  • 明確目標(biāo):要知道在哪個范圍或者網(wǎng)站去搜索
  • 爬:將所有的網(wǎng)站的內(nèi)容全部爬下來
  • ?。喝サ魧ξ覀儧]用處的數(shù)據(jù)
  • 處理數(shù)據(jù):按照我們想要的方式存儲和使用

百度貼吧爬蟲

1、規(guī)律分析:

  • 網(wǎng)頁規(guī)律
https://tieba.baidu.com/f?kw=絕地求生&ie=utf-8&pn=0
https://tieba.baidu.com/f?kw=絕地求生&ie=utf-8&pn=50
https://tieba.baidu.com/f?kw=絕地求生&ie=utf-8&pn=100

2、爬蟲 Demo

package main

import (
    "fmt"
    "net/http"
    "strconv"
    "os"
)

// 爬取網(wǎng)頁內(nèi)容
func HttpGet(url string)(result string, err error) {
    resp, err1 := http.Get(url)
    if err1 != nil {
        // print err
        err = err1
        return
    }
    
    defer resp.Body.Close()
    
    // 讀取網(wǎng)頁 Body 內(nèi)容
    buf := make([]byte, 1024 * 4)
    for {
        n, err := resp.Body.Read(buf)
        if n == 0 { // 讀取結(jié)束,或者出問題
            // print err
            break
        }
        
        result += string(buf[:n])
    }
    
    return
}

// 爬取一個網(wǎng)頁
func SpidePage(i int, page chan<- int) {
    url = "http://tieba.baidu.com/f?kw=ios&ie=utf-8&pn=0&red_tag=y1558891520&pn=" + strconv.Itoa((i - 1) * 50)
    // print url
    
    // 2) 爬,將所有的網(wǎng)站的內(nèi)容全部爬下來
    result, err := HttpGet(url) 
    if err != nil {
        // print err
        continue
    }
    
    // 把內(nèi)容寫入到文件
    fileName := strconv.Itoa((i - 1) * 50) + ".html"
    f, err1 := os.Create(fileName)
    if err1 != nil {
        // print err1
        continue
    }
    
    f.WriteString(result) // 寫內(nèi)容
    f.Close() // 關(guān)閉文件
    
    page <- i // 寫內(nèi)容
}


func DoWork(start, end int) {
    fmt.Printf("正在爬取 %d 到 %d 的頁面\b", start, end)
    
    page := make(chan int)
    
    // 1) 明確目標(biāo)(要知道你準(zhǔn)備在哪個范圍或者網(wǎng)站去搜索)
    // https://tieba.baidu.com/f?kw=絕地求生&ie=utf-8&pn=0 // 下一頁加 50
    for i := start; i < end; i++ {
        go SpidePage(i, page)
    }
    
    for i := start; i < end; i++ {
        // 沒爬完之前是阻塞的
        fmt.Printf("第%d個頁面爬取完成\n", <-page)
    }
}

func main() {
    var start, end int
    fmt.Printf("請輸入起始頁(>= 1): ")
    fmt.Scan(&start)
    fmt.Printf("請輸入終止頁(>= 起始頁): ")
    fmt.Scan(&end)
    
    DoWork(start, end)
}

段子爬蟲

1、規(guī)律分析

  • 網(wǎng)頁規(guī)律
https://www.pengfu.com/index_1.html
https://www.pengfu.com/index_2.html
https://www.pengfu.com/index_3.html
  • 主頁面規(guī)律
<h1 class="dp-b"><a href=" 一個段子 URL 連接 "
  • 段子 URL
<h1> 標(biāo)題 </h1> 只取1個
<div class="content-txt pt10"> 段子內(nèi)容 <a id="prev" href="

2、爬蟲 Demo

package main

import (
    "fmt"
    "net/http"
    "strconv"
    "regexp"
    "strings"
    //"os"
)

func HttpGet(url string)(result string, err error) {
    resp, err1 := http.Get(url)
    if err1 != nil {
        // print err
        err = err1
        return
    }
    
    defer reso.Body.Close()
    
    // 讀取網(wǎng)頁內(nèi)容
    buf := make([]byte, 4 * 1024)
    for {
        n, _ := resp.Body.Read(buf)
        if n == 0 {
            break
        }
        
        result += string(buf{:n})
    }
    return
}

func SpiderOneJoy(url string)(title, content string, err error) {
    // 開始爬取網(wǎng)頁內(nèi)容
    result, err1 := HttpGet(url)
    if err1 != nil {
        err = err1
        return
    }
    
    2) 開始爬取頁面內(nèi)容
    result, err := HttpGet(url)
    if err != nil {
        // print err
        return
    }
    fmt.Printf("r = ", result)
    
    // 3)獲取關(guān)鍵信息:標(biāo)題
    // <h1> 段子標(biāo)題 </h1> 只取1個
    re1 := regexp.MustCompile(`<h1>(?s:(.*?))</h1>`) // 正則表達(dá)式以組為單位,?s 表示遇到 \n 的也匹配
    if re1 == nil {
        err = fmt.Errorf("%s", "regex.MustCompile err")
        return
    }
    
    // 取段子標(biāo)題
    tmpTitle := re.FindAllStringSubmatch(result, 1) // 最后一個參數(shù)為 1, 表示只過濾第 1 個
    for _, data := range tmpTitle {
        title = data[1]
        
        // 對tab、制表符、換行、空格特殊處理
        title = strings.Replace(title, "\r", "",-1)
        title = strings.Replace(title, "\n", "",-1)
        title = strings.Replace(title, " ", "",-1)
        title = strings.Replace(title, "\t", "",-1)
        break
    }
    
    // 3)獲取關(guān)鍵信息:內(nèi)容
    // <div class="content-txt pt10"> 段子內(nèi)容 <a id="prev" href="
    re2 := regexp.MustCompile(`<div class="content-txt pt10">(?s:(.*?))<a id="prev" href=`) // 正則表達(dá)式以組為單位,?s 表示遇到 \n 的也匹配
    if re2 == nil {
        err = fmt.Errorf("%s", "regex.MustCompile err")
        return
    }
    
    // 取段子內(nèi)容
    tmpContent := re.FindAllStringSubmatch(result, -1) // -1 表示過濾全部
    for _, data := range tmpContent {
        content = data[1]
        
        // 對tab、制表符、換行、空格特殊處理
        content = strings.Replace(content, "\r", "",-1)
        content = strings.Replace(content, "\n", "",-1)
        content = strings.Replace(content, " ", "",-1)
        content = strings.Replace(content, "\t", "",-1)
        content = strings.Replace(content, "<br />", "",-1)
        break
    }
    
    return
}

// 把內(nèi)容寫入到文件
func StoreJoyToFile(i int, fileTitle, fileContent []string) {
    // 新建文件
    f, err := os.Create(strconv.IToa(i) + ".txt")
    if err != nil {
        // print err
        return
    }
    
    defer f.Close()
    
    // 寫內(nèi)容
    n := len(fileTitle)
    for i := 0; i < n; i++ {
        // 寫標(biāo)題
        f.WriteString(fileTitle[i] + "\n")
        // 寫內(nèi)容
        f.WriteString(fileContent[i] + "\n")
        
        f.WriteString("\n==============\n")
    }
}

// 爬取主頁面
func SpidePage(i int) {
    // 1) 明確爬取的 url
    // url: https://www.pengfu.com/index_1.html
    url := "https://www.pengfu.com/index_" + strconv.IToa(i) + ".html"
    fmt.Printf("正在爬取滴%d個網(wǎng)頁:%s", i, url)
    
    // 2) 開始爬取頁面內(nèi)容
    result, err := HttpGet(url)
    if err != nil {
        // print err
        return
    }
    fmt.Printf("r = ", result)
    
    // 3) 取內(nèi)容,正則匹配
    // <h1 class="dp-b"><a href=" 一個段子 URL 連接 " 
    // 解析表達(dá)式,取關(guān)鍵信息
    re := regexp.MustCompile(`<h1 class="dp-b"><a href="(?s:(.*?))"`) // 正則表達(dá)式以組為單位,?s 表示遇到 \n 的也匹配
    if re == nil {
        // print err
        return
    }
    
    // 去關(guān)鍵信息: 段子詳情頁的 URL
    joyUrls := re.FindAllStringSubmatch(result, -1)
    fmt.Println("joyUrl = %s", joyUrls)
    
    fileTitle := make([]string, 0)
    fileContent := make([]string, 0)
    
    // joyUrls:[[<h1 class="dp-b"><a https://www.pengfu.com/content_1788974_1.html]
    
    // 獲取 joyUrl
    // 切片迭代,第一個返回下標(biāo),第二個返回內(nèi)容
    for _, data := range joyUrls {
        // print url
        // fmt.Println("url = ", data[1])
        // 爬取每一個段子
        title, content, err :=  SpiderOneJoy(data[1])
        if err != nil {
            // print err
            continue
        }
        
        // print title、content
        fileTitle = append(fileTitle, title) // 追加內(nèi)容
        fileContent = append(fileContent, content) // 追加內(nèi)容
    }
    
    // print fileTitle、fileContent
    
    // 把內(nèi)容寫入到文件
    StoreJoyToFile(i, fileTitle, fileContent)
}

func DoWork(start, end int) {
    fmt.Printf("正在爬取 %d 到 %d 的頁面\b", start, end)
    
    page := make(chan int)
    
    // 1) 明確目標(biāo)(要知道你準(zhǔn)備在哪個范圍或者網(wǎng)站去搜索)
    // 
    for i := start; i < end; i++ {
        go SpidePage(i, page)
    }
    
    for i := start; i < end; i++ {
        // 沒爬完之前是阻塞的
        fmt.Printf("第%d個頁面爬取完成\n", <-page)
    }  
}

func main() {
    var start, end int
    fmt.Printf("請輸入起始頁(>= 1): ")
    fmt.Scan(&start)
    fmt.Printf("請輸入終止頁(>= 起始頁): ")
    fmt.Scan(&end)
    
    DoWork(start, end)
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容