Go 和 Colly筆記


Colly是Go下功能比較完整的一個HTTP客戶端工具.

安裝

Win10

下載zip包, 直接解壓至c:根目錄. 如果不打算直接命令行使用, 可以不配置環境變量

Ubuntu

下載tar.gz, 解壓至/opt, 可以不配置環境變量

Golang里的協程同步(等價於Java中的鎖)

Mutex

在Go程序中為解決Race Condition和Data Race問題, 使用Mutex來鎖定資源只能同時被一個協程調用, 通過 &sync.Mutex() 創建一個全局變量, 在子方法里面通過Lock()和Unlock()鎖定和釋放資源. 注意defer關鍵字的使用.

import (
	"strconv"
	"sync"
)

var myBalance = &balance{amount: 50.00, currency: "GBP"}

type balance struct {
	amount   float64
	currency string
	mu       sync.Mutex
}

func (b *balance) Add(i float64) {
	b.mu.Lock()
	b.amount += i
	b.mu.Unlock()
}

func (b *balance) Display() string {
	b.mu.Lock()
	defer b.mu.Unlock()
	return strconv.FormatFloat(b.amount, 'f', 2, 64) + " " + b.currency
}

讀寫鎖使用RWMutex, 在Mutex的基礎上, 增加了RLock()和RUnlock()方法. 在Lock()時依然是互斥的, 但是RLock()與RLock()之間不互斥

import (
	"strconv"
	"sync"
)

var myBalance = &balance{amount: 50.00, currency: "GBP"}

type balance struct {
	amount   float64
	currency string
	mu       sync.RWMutex
}

func (b *balance) Add(i float64) {
	b.mu.Lock()
	b.amount += i
	b.mu.Unlock()
}

func (b *balance) Display() string {
	b.mu.RLock()
	defer b.mu.RUnlock()
	return strconv.FormatFloat(b.amount, 'f', 2, 64) + " " + b.currency
}

 Channel

Channel類似於Java中的Semaphore, 通過設置channel容量限制同時工作的協程數, channel滿了之后協程會被阻塞

package main                                                                                                                                                           

import (
    "fmt"
    "time"
    "strconv"
)

func makeCakeAndSend(cs chan string) {
    for i := 1; i<=3; i++ {
        cakeName := "Strawberry Cake " + strconv.Itoa(i)
        fmt.Println("Making a cake and sending ...", cakeName)
        cs <- cakeName //send a strawberry cake
    }   
}

func receiveCakeAndPack(cs chan string) {
    for i := 1; i<=3; i++ {
        s := <-cs //get whatever cake is on the channel
        fmt.Println("Packing received cake: ", s)
    }   
}

func main() {
    cs := make(chan string)
    go makeCakeAndSend(cs)
    go receiveCakeAndPack(cs)

    //sleep for a while so that the program doesn’t exit immediately
    time.Sleep(4 * 1e9)
}

 可以設置channel的容量 

c := make(chan Type, n)

 

Go的語法

Go的語法簡介, 這一篇寫得很好 https://zhuanlan.zhihu.com/p/98556883

Go語言的點括號語法

對於下面的語句

mpl := playlist.(*m3u8.MediaPlaylist)

表示將前面的對象轉為 *m3u8.MediaPlaylist 類型, 

這種類型轉換用於在前面的表達式返回的結果存在多種可能時, 需要在使用前對類型進行固定. 也可以用於類型查詢.

# 查詢接口指向的對象實例是否是*MyStruct類型
if v1.(*MyStruct)

# 查詢接口指向的對象實例是否實現了MyInterface接口,要在運行期確定
if v2.(MyInterface)

又如

func DecodeWith(input interface{}, strict bool, customDecoders []CustomDecoder) (Playlist, ListType, error) {
	switch v := input.(type) {
	case bytes.Buffer:
		return decode(&v, strict, customDecoders)
	case io.Reader:
		buf := new(bytes.Buffer)
		_, err := buf.ReadFrom(v)
		if err != nil {
			return nil, 0, err
		}
		return decode(buf, strict, customDecoders)
	default:
		return nil, 0, errors.New("input must be bytes.Buffer or io.Reader type")
	}
}

調用

f, err := os.Open(testCase.src)
if err != nil {
	t.Fatal(err)
}
p, listType, err := DecodeWith(bufio.NewReader(f), true, testCase.customDecoders)

強制類型轉換語法檢測是否實現接口

_ Error = (*_Error)(nil)

這個一個強制類型轉換語法檢測是否實現接口的功能,nil就是空指針地址就是0,一個變量是具有類型和地址兩個屬性,強制類型轉換只修改了類型,但是地址是原來那個(例如是nil),這樣的轉換的變量不用分配地址。例如下列代碼:

var _ Context = (*ContextBase)(nil)

nil的類型是nil, 地址值為0,利用強制類型轉換成了*ContextBase,返回的變量就是類型為*ContextBase地址值為0,然后Context=xx賦值, 如果xx實現了Context接口就沒事,如果沒有實現在編譯時期就會報錯,實現編譯期間檢測接口是否實現。

參考: golang中的四種類型轉換總結   https://segmentfault.com/a/1190000022255009

Go的接口和實現類

Go代碼中使用interface關鍵字標識一個接口定義,例如

type Device interface {
	Flush() error                   // flush all previous writes to the device
	MTU() (int, error)              // returns the MTU of the device
	Name() (string, error)          // fetches and returns the current name
	Events() chan Event             // returns a constant channel of events related to the device
	Close() error                   // stops the device and closes the event channel
}

但是對於這個接口的實現類,並不顯式地聲明與這個接口的關系,只要是實現了這些方法的結構體,都可以看作是這個接口的實現類

type NativeTun struct {
	name        string
	tunFile     *os.File
	events      chan Event
	errors      chan error
	routeSocket int
}

func (tun *NativeTun) Name() (string, error) {
	var name string
	...
	return name, nil
}

func (tun *NativeTun) File() *os.File {
	return tun.tunFile
}

func (tun *NativeTun) Events() chan Event {
	return tun.events
}

func (tun *NativeTun) Read(buff []byte, offset int) (int, error) {
	select {
	case err := <-tun.errors:
	...
	}
}

 

Go函數的不定參數

Go中可以使用不定參數, 如果有多個參數, 不定參數必須是參數列表中的最后一個

func showName(a ...string)  {
	name := strings.Join(a," ")
	fmt.Println(name)
}

使用不定參數時, 可以傳入該類型切片的展開形式, 但是如果傳入的是展開形式, 則其前后都不能再添加同類型參數, 例如

func main() {
    name := []string{"11","22","33"}
    showName(name...)
}

func showName(a ...string)  {
    fmt.Println(strings.Join(a," "))
}

如果對showName(a ...string) 使用showName("test", name...) 或 showName(name..., "test")都會報語法錯誤.

但是對於func New(ctx context.Context, opts ...Option) (host.Host, error) , 可以使用 New(context.Background(), opts...)

如果在函數內修改了切片內的元素, 會影響到原切片.

Go 教程

網絡編程 https://tumregels.github.io/Network-Programming-with-Go/

Go常用Package

time

用法詳解 https://juejin.im/post/5ae32a8651882567105f7dd3

 

使用GoLand作為開發環境

GOROOT: go目錄放到了/opt/go, 所以GOROOT默認指向的也是/opt/go

GOPATH: 在Settings->Go->GOPATH里Global GOPATH留空,設置項目的GOPATH, 指向 /home/milton/WorkGo

GOPROXY: 在Settings->Go->Go Modules下, 設置 Environments, GOPROXY=https://goproxy.cn

在GoLand內部的Terminal里查看環境變量, 命令 go env, 確認路徑無誤, 然后執行以下命令安裝

# v1
go get -u github.com/gocolly/colly

# v2
go get -u github.com/gocolly/colly/v2

下載項目依賴

# 在項目目錄下運行
go mod download

 

基礎使用

增加import

import "github.com/gocolly/colly/v2"

調用

func main() {
	// Instantiate default collector
	c := colly.NewCollector(
		// Visit only domains: hackerspaces.org, wiki.hackerspaces.org
		colly.AllowedDomains("hackerspaces.org", "wiki.hackerspaces.org"),
	)

	// On every a element which has href attribute call callback
	c.OnHTML("a[href]", func(e *colly.HTMLElement) {
		link := e.Attr("href")
		// Print link
		fmt.Printf("Link found: %q -> %s\n", e.Text, link)
		// Visit link found on page
		// Only those links are visited which are in AllowedDomains
		c.Visit(e.Request.AbsoluteURL(link))
	})

	// Before making a request print "Visiting ..."
	c.OnRequest(func(r *colly.Request) {
		fmt.Println("Visiting", r.URL.String())
	})

	// Start scraping on https://hackerspaces.org
	c.Visit("https://hackerspaces.org/")
}

  

使用代理池

參考文檔中的例子 http://go-colly.org/docs/examples/proxy_switcher/  這里的例子要注意兩個問題

1. 初始化時, 需要設置AllowURLRevisit, 否則在訪問同一URL時會直接跳過返回之前的結果

c := colly.NewCollector(colly.AllowURLRevisit())

2. 還需要設置禁用KeepAlive, 否則在多次訪問同一網址時, 只會調用一次GetProxy, 這樣達不到輪詢代理池的效果, 相關信息 #392#366 , #339 

c := colly.NewCollector(colly.AllowURLRevisit())

c.WithTransport(&http.Transport{
	DisableKeepAlives: true,
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM