猫史档案馆


Golang爬虫语言接入代理

用户:LaicalLaical查看:0 回复:0 评论:0 创建时间:2020-09-09T17:51:45


golang语言也是爬虫中的一种框架语言。当然很多网络爬虫新手都会面临选择什么语言适合于爬虫。一般很多爬虫用户都会选择python和java框架语言来写爬虫程序从而进行采集数据。其实除了python和java框架语言还有很多语言都适合数据采集。只不过python和JAVA语言框架比较符合大家的选择性。我这里选择的就是golang语言调用自己的爬虫程序。只要了解爬虫原理,不管用什么编程语言,基本上都是可以写出一个爬虫系统的。无论用什么爬虫语言框架,长期使用一个IP去采集数据,肯定会收到限制。这种时候就需要使用爬虫代理去解决问题。

golang爬虫步骤:

1、制定爬虫目标

2、制定一个爬虫接口

3、发出HTTP,获取数据

4、屏蔽无效请求

5、解析数据内容

6、储存数据

7、使用爬虫代理持续采集

以下是golang语言配置爬虫代理代码demo :
        package main

        import (
            "net/url"
            "net/http"
            "bytes"
            "fmt"
            "io/ioutil"
        )

        // 代理服务器(产品官网 www.16yun.cn)
        const ProxyServer = "t.16yun.cn:31111"

        type ProxyAuth struct {
            Username string
            Password string
        }

        func (p ProxyAuth) ProxyClient() http.Client {

            var proxyURL *url.URL
            if p.Username != ""&& p.Password!="" {
                proxyURL, _ = url.Parse("http://" + p.Username + ":" + p.Password + "@" + ProxyServer)
            }else{
                proxyURL, _ = url.Parse("http://" + ProxyServer)
            }
            return http.Client{Transport: &http.Transport{Proxy:http.ProxyURL(proxyURL)}}
        }

        func main()  {


            targetURI := "https://httpbin.org/ip"


            // 初始化 proxy http client
            client := ProxyAuth{"username",  "password"}.ProxyClient()

            request, _ := http.NewRequest("GET", targetURI, bytes.NewBuffer([] byte(``)))

            // 设置Proxy-Tunnel
            // rand.Seed(time.Now().UnixNano())
            // tunnel := rand.Intn(10000)
            // request.Header.Set("Proxy-Tunnel", strconv.Itoa(tunnel) )

            response, err := client.Do(request)

            if err != nil {
                panic("failed to connect: " + err.Error())
            } else {
                bodyByte, err := ioutil.ReadAll(response.Body)
                if err != nil {
                    fmt.Println("读取 Body 时出错", err)
                    return
                }
                response.Body.Close()

                body := string(bodyByte)

                fmt.Println("Response Status:", response.Status)
                fmt.Println("Response Header:", response.Header)
                fmt.Println("Response Body:\n", body)
            }
        }


回复

上一页1 页 / 共 0下一页