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,
})

 

posted on 2020-06-11 15:28  Milton  阅读(992)  评论(0编辑  收藏  举报

导航