脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - go colly 爬虫实现示例

go colly 爬虫实现示例

2022-11-24 10:47如此风景 Golang

这篇文章主要为大家介绍了go colly 爬虫实现示例,效果是根据输入的浏览器cookie及excel必要行列号,从excel中读取公司名称,查询公司法人及电话号码。并写回到excel中指定行

正文

贡献某CC,go源码爬虫一个,基于colly,效果是根据输入的浏览器cookie及excel必要行列号,从excel中读取公司名称,查询公司法人及电话号码。并写回到excel中指定行。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package main
import (
   "bufio"
   "fmt"
   "github.com/gocolly/colly/debug"
   "github.com/gocolly/colly/extensions"
   "github.com/xuri/excelize/v2"
   "net/url"
   "os"
   "runtime"
   "strconv"
   "time"
)
import "github.com/gocolly/colly"
var (
   cookies string
   tempUrl string
   tempGongSiName string
   tempI int
)
func main() {
   //要处理的文件全名
   var fileName string
   //列的名称
   var namelie string
   //开始行号
   var startNum int
   //结束行号
   var endNum int
   var personLie string
   var phoneLie string
   fmt.Println("请输入浏览器cookies 在浏览器 开发者模式F12,情况下找到控制台(consol) 输入(注意,Cookie中如果有 HttpOnly的需要在开发工具中将HttpOnly取消掉,然后再执行后面命令):document.cookie  即可,然后复制出来! 右击,复制字符串内容")
   //fmt.Scan(&cookies)  //此行遇到空格会 默认输入完毕了,所以不能用它
   reader := bufio.NewReader(os.Stdin)
   res, _, err := reader.ReadLine()
   if nil == err {
      cookies=string(res)
   }else{
      fmt.Println("读取cookie错误 error:", err)
      return
   }
   //fmt.Println("输入的cookie是:"+cookies)
   fmt.Println("请输入文件全路径:(字符串类型)")
   fmt.Scan(&fileName)
   fmt.Println("请输入Excel要查询公司名称列的字母(字母大写):")
   fmt.Scan(&namelie)
   fmt.Println("请输入Excel指定列的第一个行号(数字类型):")
   fmt.Scan(&startNum)
   fmt.Println("请输入Excel指定列的最后一个行号(数字类型):")
   fmt.Scan(&endNum)
   fmt.Println("请输入Excel联系人的所在列的字母(字母大写):")
   fmt.Scan(&personLie)
   fmt.Println("请输入Excel联系电话所在列的字母(字母大写):")
   fmt.Scan(&phoneLie)
   //输出所有输入的信息,验证正确
   //fmt.Println(fileName,namelie,startNum,endNum,personLie,phoneLie)
   f, err := excelize.OpenFile(fileName)
   if err!=nil {
      fmt.Println(err)
      return
   }
   c:=initCollector(f,personLie,phoneLie)
   //上面打开的工作簿记得关闭吆。
   defer func() {
      // 关闭工作簿
      if err := f.Close(); err != nil {
         fmt.Println(err)
      }
   }()
   for i:=startNum;i<=endNum;i++{
      // 获取工作表中指定单元格的值
      cell, err := f.GetCellValue("Sheet1", namelie+strconv.Itoa(i))
      if err != nil {
         fmt.Println("读取第"+strconv.Itoa(i)+"行出错!")
         return
      }else{
         fmt.Println("开始抓取:"+cell+"  数据")
         tempGongSiName = cell
         tempI = i
         visitUrl(c)
         time.Sleep(1*time.Second)
      }
   }
   fmt.Println("-------------亲爱的,程序成功执行完毕。--------我要喝咖啡,我要吃肉肉------!")
}
///初始化收集器
func initCollector(f *excelize.File,personLie string,phoneLie string,) *colly.Collector {
   c := colly.NewCollector(colly.MaxDepth(1), colly.Debugger(&debug.LogDebugger{}))
   extensions.RandomUserAgent(c)                              // 使用随机的UserAgent,最好能使用代理。这样就不容易被ban
   c.SetProxy("socks5://127.0.0.1:7890")
   c.OnError(func(response *colly.Response, err error) {
      fmt.Println("---->onError  --------爬取出错了"+err.Error())
      runtime.Goexit()
   })
   c.OnResponse(func(response *colly.Response) {
      fmt.Println("---->onResponse")
   })
   c.OnXML("table", func(element *colly.XMLElement) {
      fmt.Println("---->onXML")
   })
   c.OnRequest(func(r *colly.Request) {
      r.Headers.Set("Cookie",cookies)
      r.Headers.Add("referer", tempUrl)
      r.Headers.Add("sec-fetch-mode", "cors")
      r.Headers.Add("sec-fetch-site", "same-origin")
      r.Headers.Add("accept", "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01")
      r.Headers.Add("accept-encoding", "gzip, deflate, br")
      r.Headers.Add("accept-language", "en,zh-CN;q=0.9,zh;q=0.8")
      r.Headers.Add("X-Requested-With", "XMLHttpRequest")
   })
   c.OnHTML("tr:first-child", func(e *colly.HTMLElement) {//拿到查询的第一条数据。
      fmt.Println("---->onHtml---获取成功!")
      //拿到第一条的公司主要信息。
      //fmt.Println("---->"+e.DOM.Find(".relate-info").Text())
      sellectEle := e.DOM.Find(".relate-info")
      //最终查询出来的人
      name:=sellectEle.Find("div:nth-child(1)").Find("div>span").First().Find("a").Text()
      //最终查询出来的电话
      phone:=sellectEle.Find("div:nth-child(2)").Find("div>span").First().Find("span>span").Find(":nth-child(2)").Text()
      //fmt.Println("--->>>"+name)
      //fmt.Println("--->>>"+phone)
      f.SetCellValue("Sheet1", personLie+strconv.Itoa(tempI), name)
      fmt.Println("将"+tempGongSiName+"人名 ("+name+") 写入  "+personLie+strconv.Itoa(tempI))
      f.SetCellValue("Sheet1", phoneLie+strconv.Itoa(tempI), phone)
      fmt.Println("将"+tempGongSiName+"电话 ("+phone+") 写入  "+phoneLie+strconv.Itoa(tempI))
      f.Save()
   })
   c.OnScraped(func(response *colly.Response) {
      fmt.Println("onScraped")
   })
   return c
}
//访问给定名称
func visitUrl(c *colly.Collector){
   tempUrl:="https://www.xxx.com/web/search?key="+url.QueryEscape(tempGongSiName)
   c.Visit(tempUrl)
}

以上就是go colly 爬虫实现示例的详细内容,更多关于go colly 爬虫的资料请关注服务器之家其它相关文章!

原文链接:https://juejin.cn/post/7148752862388944926

延伸 · 阅读

精彩推荐
  • Golang三种Golang数组拷贝方式及性能分析详解

    三种Golang数组拷贝方式及性能分析详解

    在Go语言中,我们可以使用for、append()和copy()进行数组拷贝。这篇文章主要为大家详细介绍一下这三种方式的具体实现与性能分析,需要的可以参考一下...

    jiaxwu11442022-08-24
  • Golang使用Go实现优雅重启服务功能

    使用Go实现优雅重启服务功能

    这篇文章主要介绍了如何使用Go来实现优雅重启服务,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下 ...

    songsong0013662020-05-29
  • GolangGo Println和Printf的区别详解

    Go Println和Printf的区别详解

    这篇文章主要介绍了Go Println和Printf的区别详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    冷月醉雪11252021-02-27
  • Golang一文详解Go语言单元测试的原理与使用

    一文详解Go语言单元测试的原理与使用

    Go语言中自带有一个轻量级的测试框架testing和自带的go test命令来实现单元测试和性能测试。本文将通过示例详细聊聊Go语言单元测试的原理与使用,需要的...

    山与路4072022-11-22
  • GolangGo 标准库 net/url 学习笔记

    Go 标准库 net/url 学习笔记

    本文是一篇学习笔记,记录了作者学习 go 语言标准库 net/url 库的过程。...

    马哥Linux运维5962021-08-31
  • Golanggolang实现命令行程序的使用帮助功能

    golang实现命令行程序的使用帮助功能

    这篇文章介绍了golang实现命令行程序使用帮助的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以...

    taadis9542022-07-13
  • GolangGolang 错误捕获Panic与Recover的使用

    Golang 错误捕获Panic与Recover的使用

    对于Go语言的错误是通过返回值的方式,本文主要介绍了Golang 错误捕获Panic与Recover的使用,文中根据实例编码详细介绍的十分详尽,具有一定的参考价值,...

    头秃猫轻王8662022-09-08
  • GolangVSCode配置Go插件和第三方拓展包的详细教程

    VSCode配置Go插件和第三方拓展包的详细教程

    这篇文章主要介绍了VSCode配置Go插件和第三方拓展包的详细教程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可...

    WindSun20512020-07-05