Go爬虫(http、goquery和colly)详解

作者:Golang-Study 时间:2024-05-08 10:52:43 

1、net/http爬虫

net/http配合正则表达式爬虫。

Go爬虫(http、goquery和colly)详解

package main

import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
"sync"
)

// 负责抓取页面的源代码(html)
// 通过http包实现
func fetch(url string) string {

// 得到一个客户端
client := &http.Client{}
request, _ := http.NewRequest("GET", url, nil)

request.Header.Set("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Mobile Safari/537.36")
request.Header.Add("Cookie", "test_cookie=CheckForPermission; expires=Tue, 30-Aug-2022 01:04:32 GMT; path=/; domain=.doubleclick.net; Secure; HttpOnly; SameSite=none")

// 客户端发送请求,并且获取一个响应
response, err := client.Do(request)
if err != nil {
log.Println("Error: ", err)
return ""
}

// 如果状态码不是200,就是响应错误
if response.StatusCode != 200 {
log.Println("Error: ", response.StatusCode)
return ""
}

defer response.Body.Close() // 关闭

// 读取响应体中的所有数据到body中,这就是需要的部分
body, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Println("Error: ", err)
return ""
}

// 转换为字符串(字节切片 --> 字符串)
return string(body)
}

var waitGroup sync.WaitGroup

// 解析页面源代码
func parseURL(body string) {

// 将body(响应结果)中的换行替换掉,防止正则匹配出错
html := strings.Replace(body, "\n", "", -1)
// 正则匹配
re_Img_div := regexp.MustCompile(`<div class="img_wrapper">(.*?)</div>`)

img_div := re_Img_div.FindAllString(html, -1) // 得到<div><img/></div>

for _, v := range img_div {

// img正则
re_link := regexp.MustCompile(`src="(.*?)"`)
// 找到所有的图片链接
links := re_link.FindAllString(v, -1) // 得到所有图片链接

// 遍历links,切掉不必要的部分src="和最后的"
for _, v := range links {

src := v[5 : len(v)-1]
src = "http:" + src

waitGroup.Add(1)
go downLoad(src)
}
}

}

// 下载
func downLoad(src string) {

fmt.Println("================================", src)

// 取一个文件名
filename := string(src[len(src)-8 : len(src)])
fmt.Println(filename)

response, _ := http.Get(src)
picdata, _ := ioutil.ReadAll(response.Body)

image, _ := os.Create("./files/" + filename)
image.Write(picdata)

defer func() {
image.Close()
waitGroup.Done()
}()
}

func main() {

url := "http://games.sina.com.cn/t/n/2021-01-15/kftpnnx7445951.shtml"

body := fetch(url)
// fmt.Println(body)
parseURL(body)

waitGroup.Wait()
}

Go爬虫(http、goquery和colly)详解

2、goquery库爬虫

goquery可以避免操作复杂的正则表达式,它可以直接根据url获取一个Document对象,然后根据标签选择器、类选择器和id选择器获取相应的选择对象,进行自定义的操作。

goquery可以灵活的获取页面中的元素。

*** 一个简单的例子,引出goquery中的重要API

package main

import (
"fmt"
"strings"

"github.com/PuerkitoBio/goquery"
)

func main() {

url := "http://games.sina.com.cn/t/n/2021-01-15/kftpnnx7445951.shtml"

// 得到页面原文档对象
d, _ := goquery.NewDocument(url)

// 根据文档对象借助类选择器获取Selection对象,通过Each遍历所有的适配类选择器的对象
// Each的参数是一个函数,里面是处理逻辑
d.Find("img").Each(func(index int, s *goquery.Selection) {

// 根据属性名获取属性值   一个Selection对象 --> <img src="http://localhost:8080/images" > text </img>
text, _ := s.Attr("src")

// 只处理gif动态图片
if strings.HasSuffix(text, ".gif") {
text = "http:" + text
fmt.Println(text)
}

})
}

Go爬虫(http、goquery和colly)详解

*** 操作一、获取html整个原文档

分别是goquery.NewDocument(url string)goquery.NewDocumentFromResponse(*http.Response)goquery.NewDocumentFromReader(*io.Reader)。三种方式的第一种比较最为方便使用。

package main

import (
"log"
"net/http"
"strings"

"github.com/PuerkitoBio/goquery"
)

/*
goquery得到Document对象的3种方式
*/

// 1、通过NewDocument传入一个URL地址
func GetDocument_1(url string) string {

document, _ := goquery.NewDocument(url)

document.Find("href")

return "document.Text()"
}

// 2、通过响应获取。第一种方式是第二种方式的封装
func GetDocument_2(url string) string {

client := &http.Client{}
request, _ := http.NewRequest("GET", url, nil)

response, _ := client.Do(request)
document, err := goquery.NewDocumentFromResponse(response)

if err != nil {
log.Fatalln(err)
}
document.Find("")

return ""
}

// 3、有一个html文本的情况下,读取转换为Document对象
func GetDocument_3(html string) string {

document, _ := goquery.NewDocumentFromReader(strings.NewReader(html))
document.Find("")

return ""
}

*** 操作二、选择器
同html的标识方式,在Find函数中。

*** 操作三、Selection相关方法

Go爬虫(http、goquery和colly)详解

*** 最后来完成net/http中的网页爬虫

package main

import (
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"sync"

"github.com/PuerkitoBio/goquery"
)

var lock sync.WaitGroup

func main() {

url := "http://games.sina.com.cn/t/n/2021-01-15/kftpnnx7445951.shtml"

// 得到页面原文档对象
d, _ := goquery.NewDocument(url)

// 根据文档对象借助类选择器获取Selection对象,通过Each遍历所有的适配类选择器的对象
// Each的参数是一个函数,里面是处理逻辑
d.Find("img").Each(func(index int, s *goquery.Selection) {

// 根据属性名获取属性值   一个Selection对象 --> <img src="http://localhost:8080/images" > text </img>
text, _ := s.Attr("src")

// 只处理gif动态图片
if strings.HasSuffix(text, ".gif") {
lock.Add(1)

http := "http:" + text

// 得到图片地址,开启协程下载图片
go downLoading(http)
}

})

lock.Wait()
}

func downLoading(src string) {

fmt.Println("================================", src)

// 取一个文件名
filename := string(src[len(src)-8 : len(src)])
fmt.Println(filename)

response, _ := http.Get(src)
picdata, _ := ioutil.ReadAll(response.Body)

image, _ := os.Create("./files/" + filename)
image.Write(picdata)

defer func() {
image.Close()
lock.Done()
}()
}

Go爬虫(http、goquery和colly)详解

3、colly框架爬虫

首先要获取一个*colly.Collector对象;
然后注册处理函数OnXxx函数;
之后就可以访问url了。

*** OnXxx函数
主要操作都是由OnXxx函数的参数函数进行处理的

Go爬虫(http、goquery和colly)详解

*** 完成图片的爬取

package main

import (
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"sync"

"github.com/gocolly/colly"
)

var locker sync.WaitGroup

func main() {

col := colly.NewCollector()

// 检测请求
col.OnRequest(func(req *colly.Request) {
fmt.Println("检测一个请求......")
})

// 检测响应
col.OnResponse(func(r *colly.Response) {
fmt.Println("检测一个响应......")
})

// 定位img标签。注册该函数,框架内部回调
col.OnHTML("img", func(elem *colly.HTMLElement) {

fmt.Println("ONXHTML")

// 获取标签对应属性的值。
// 其他对标签的操作,可以查看对应的API
http := elem.Attr("src")

if strings.HasSuffix(http, ".gif") {

locker.Add(1)

http := "http:" + http

go DownLoad(http)
}
})

col.Visit("http://games.sina.com.cn/t/n/2021-01-15/kftpnnx7445951.shtml")

locker.Wait()
}

func DownLoad(src string) {

fmt.Println("================================", src)

// 取一个文件名
filename := string(src[len(src)-8 : len(src)])
fmt.Println(filename)

response, _ := http.Get(src)
picdata, _ := ioutil.ReadAll(response.Body)

image, _ := os.Create("./files/" + filename)
image.Write(picdata)

defer func() {
image.Close()
locker.Done()
}()
}

Go爬虫(http、goquery和colly)详解

Go爬虫(http、goquery和colly)详解

来源:https://blog.csdn.net/m0_73293551/article/details/126608934

标签:Go,爬虫,goquery,colly
0
投稿

猜你喜欢

  • python匿名函数lambda原理及实例解析

    2023-01-05 02:55:07
  • asp如何在数据库中用好Transaction?

    2010-06-22 21:07:00
  • SQL Server中查看对象定义的SQL语句

    2024-01-18 05:52:43
  • VUE+elementui面包屑实现动态路由详解

    2024-05-02 17:11:47
  • 鼠标双击滚动屏幕单击停止代码

    2008-02-21 11:44:00
  • 讲解Python中for循环下的索引变量的作用域

    2022-11-27 18:41:05
  • PHP魔术方法__ISSET、__UNSET使用实例

    2024-05-22 10:09:08
  • javascript中判断一个值是否在数组中并没有直接使用

    2024-05-13 10:38:28
  • 原生JS与jQuery编写简单选项卡

    2024-04-30 09:52:52
  • Python 制作自动化翻译工具

    2022-08-17 05:34:50
  • go语言中的面向对象

    2024-01-31 17:04:13
  • Python3访问并下载网页内容的方法

    2022-11-12 06:08:39
  • 基于python 的Pygame最小开发框架

    2022-01-23 12:22:40
  • Python必考的5道面试题集合

    2021-07-11 19:38:41
  • 在python中使用requests 模拟浏览器发送请求数据的方法

    2022-05-05 03:17:35
  • 如何让利用Python+AI使静态图片动起来

    2022-06-06 08:15:31
  • pytorch中的embedding词向量的使用方法

    2022-03-25 09:05:27
  • Python程序员面试题 你必须提前准备!

    2023-09-12 09:52:44
  • python中的annotate函数使用

    2021-04-10 01:52:59
  • 古老的问题:清除浮动

    2009-02-12 11:21:00
  • asp之家 网络编程 m.aspxhome.com