有名的爬虫框架 colly 的特性及2个详细采集案例

2024-03-25 12:04

本文主要是介绍有名的爬虫框架 colly 的特性及2个详细采集案例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一. Colly概述

前言:colly 是 Go 实现的比较有名的一款爬虫框架,而且 Go 在高并发和分布式场景的优势也正是爬虫技术所需要的。它的主要特点是轻量、快速,设计非常优雅,并且分布式的支持也非常简单,易于扩展。

框架简介:基于colly框架及net/http进行封装,实现的一款可配置分布式爬虫架构。使用者只需要配置解析、并发数、入库topic、请求方式、请求url等参数即可,其他代码类似于scrapy,不需要单独编写。

colly官网地址:https://go-colly.org/
github地址: http://github.com/gocolly/colly

colly特性

  • 干净的API
  • 快速(单核>1k请求/秒)
  • 管理每个域的请求延迟和最大并发性
  • 自动cookie和会话处理
  • 同步/异步并行抓取
  • 分布式抓取
  • 缓存
  • 非unicode响应的自动编码
  • robots. txt的支持
  • 抓取深度控制
  • 设置跨域开关
  • 谷歌应用程序引擎支持

二. colly安装及基本使用

安装go get -u github.com/gocolly/colly/...

基本使用

package mainimport ("fmt""github.com/gocolly/colly"
)func main() {// Instantiate default collectorc := colly.NewCollector(// Visit only domains: hackerspaces.org, wiki.hackerspaces.orgcolly.AllowedDomains("hackerspaces.org", "wiki.hackerspaces.org"),)// On every a element which has href attribute call callbackc.OnHTML("a[href]", func(e *colly.HTMLElement) {link := e.Attr("href")// Print linkfmt.Printf("Link found: %q -> %s\n", e.Text, link)// Visit link found on page// Only those links are visited which are in AllowedDomainsc.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.orgc.Visit("https://hackerspaces.org/")
}

三. 基于colly的2个使用案例

案例1

package mainimport ("fmt""time""github.com/gocolly/colly"
)func main() {ua := "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"c := colly.NewCollector(colly.UserAgent(ua),                      // 设置UAcolly.DetectCharset(),                    // 自动编码,防止乱码colly.AllowedDomains("www.tcmap.com.cn"), // 限制域名)c.AllowURLRevisit = true                  // 另外一种设置方式,允许重复访问_ = c.SetProxy("socks://127.0.0.1:10808") // 设置代理// 响应内容是HTML时调用,goquerySelector来查找元素c.OnHTML("a[href*=\"shandong\"]", func(h *colly.HTMLElement) {// fmt.Println(h.Text)href := h.Request.AbsoluteURL(h.Attr("href")) // 绝对路径_ = h.Request.Visit(href)// 接收上下文传递过来的数据city := h.Response.Ctx.Get("city")fmt.Println(city)})_ = c.Limit(&colly.LimitRule{DomainGlob:  "*",RandomDelay: 1 * time.Second, // 延时})// 请求前调用c.OnRequest(func(r *colly.Request) {fmt.Println("访问:", r.URL)// 从请求往响应传递上下文数据r.Ctx.Put("city", "城市")})// 收到响应后调用c.OnResponse(func(r *colly.Response) {// fmt.Println(string(r.Body))})// 通过xpath来获取元素c.OnXML("//", func(element *colly.XMLElement) {})// 请求发生错误时调用c.OnError(func(r *colly.Response, err error) {fmt.Println(err)})c.Visit("http://www.tcmap.com.cn/shandong/")
}

案例2

package mainimport ("fmt""github.com/gocolly/colly""gorm.io/driver/mysql""gorm.io/gorm""time"
)func main() {dsn := "root:pass@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"db, err := gorm.Open(mysql.New(mysql.Config{DSN:               dsn,DefaultStringSize: 256,}), &gorm.Config{})if err != nil {fmt.Println("连结数据库失败")}ua := "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"c := colly.NewCollector(colly.UserAgent(ua),                      // 设置UAcolly.DetectCharset(),                    // 自动编码,防止乱码colly.AllowedDomains("www.tcmap.com.cn"), // 限制域名)cityCollector := c.Clone()countyCollector := c.Clone()townCollector := c.Clone()// 省 http://www.tcmap.com.cn/shandong/c.OnHTML("#pagebody #page_left > table", func(element *colly.HTMLElement) {element.ForEach("tr td:first-child", func(i int, e *colly.HTMLElement) {city := e.ChildText("a")fmt.Println(city)relative_url := e.ChildAttr("a", "href")if relative_url != "" {absURL := e.Request.AbsoluteURL(relative_url)// fmt.Println(absURL)ctx := colly.NewContext()ctx.Put("city", city)_ = cityCollector.Request("GET", absURL, nil, ctx, nil)}})})// 市 http://www.tcmap.com.cn/shandong/jinan.htmlcityCollector.OnHTML("#pagebody #page_left > table", func(element *colly.HTMLElement) {city := element.Request.Ctx.Get("city")element.ForEach("tr td:first-child", func(i int, e *colly.HTMLElement) {county := e.ChildText("a")fmt.Println(city, county)relative_url := e.ChildAttr("a", "href")if relative_url != "" {absURL := e.Request.AbsoluteURL(relative_url)//fmt.Println(absURL)ctx := colly.NewContext()ctx.Put("city", city)ctx.Put("county", county)_ = countyCollector.Request("GET", absURL, nil, ctx, nil)}})})// 区县 http://www.tcmap.com.cn/shandong/lixiaqu.htmlcountyCollector.OnHTML("#pagebody #page_left > table", func(element *colly.HTMLElement) {city := element.Request.Ctx.Get("city")county := element.Request.Ctx.Get("county")element.ForEach("tr td:first-child", func(i int, e *colly.HTMLElement) {town := e.ChildText("a")fmt.Println(city, county, town)relative_url := e.ChildAttr("a", "href")if relative_url != "" {absURL := e.Request.AbsoluteURL(relative_url)//fmt.Println(absURL)ctx := colly.NewContext()ctx.Put("city", city)ctx.Put("county", county)ctx.Put("town", town)_ = townCollector.Request("GET", absURL, nil, ctx, nil)}})})// 乡镇 http://www.tcmap.com.cn/shandong/lixiaqu_jiefanglujiedao.htmltownCollector.OnHTML("#pagebody #page_left > table", func(element *colly.HTMLElement) {city := element.Request.Ctx.Get("city")county := element.Request.Ctx.Get("county")town := element.Request.Ctx.Get("town")element.ForEach("tr td:first-child", func(i int, e *colly.HTMLElement) {village := e.ChildText("a")if village != "" {fmt.Println(city, county, town, village)_ = save(db, city, county, town, village)}})})_ = c.Limit(&colly.LimitRule{DomainGlob:  "*",RandomDelay: 1 * time.Second, // 延时})_ = c.Visit("http://www.tcmap.com.cn/shandong/")// c.Wait()
}type Village struct {ID      uint `gorm:"primaryKey"`City    stringCounty  stringTown    stringVillage string
}func (Village) TableName() string {return "village"
}func save(db *gorm.DB, city string, county string, town string, village string) error {villageRecord := Village{City: city, County: county, Town: town, Village: village}db = db.Create(&villageRecord)db = db.Commit()return nil
}

文章最后,推荐推荐一个比较好用的代理:
在这里插入图片描述

这篇关于有名的爬虫框架 colly 的特性及2个详细采集案例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/844951

相关文章

Python pandas库自学超详细教程

《Pythonpandas库自学超详细教程》文章介绍了Pandas库的基本功能、安装方法及核心操作,涵盖数据导入(CSV/Excel等)、数据结构(Series、DataFrame)、数据清洗、转换... 目录一、什么是Pandas库(1)、Pandas 应用(2)、Pandas 功能(3)、数据结构二、安

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

2025版mysql8.0.41 winx64 手动安装详细教程

《2025版mysql8.0.41winx64手动安装详细教程》本文指导Windows系统下MySQL安装配置,包含解压、设置环境变量、my.ini配置、初始化密码获取、服务安装与手动启动等步骤,... 目录一、下载安装包二、配置环境变量三、安装配置四、启动 mysql 服务,修改密码一、下载安装包安装地

RabbitMQ消费端单线程与多线程案例讲解

《RabbitMQ消费端单线程与多线程案例讲解》文章解析RabbitMQ消费端单线程与多线程处理机制,说明concurrency控制消费者数量,max-concurrency控制最大线程数,prefe... 目录 一、基础概念详细解释:举个例子:✅ 单消费者 + 单线程消费❌ 单消费者 + 多线程消费❌ 多

在macOS上安装jenv管理JDK版本的详细步骤

《在macOS上安装jenv管理JDK版本的详细步骤》jEnv是一个命令行工具,正如它的官网所宣称的那样,它是来让你忘记怎么配置JAVA_HOME环境变量的神队友,:本文主要介绍在macOS上安装... 目录前言安装 jenv添加 JDK 版本到 jenv切换 JDK 版本总结前言China编程在开发 Java

Spring Boot Actuator应用监控与管理的详细步骤

《SpringBootActuator应用监控与管理的详细步骤》SpringBootActuator是SpringBoot的监控工具,提供健康检查、性能指标、日志管理等核心功能,支持自定义和扩展端... 目录一、 Spring Boot Actuator 概述二、 集成 Spring Boot Actuat

Python Web框架Flask、Streamlit、FastAPI示例详解

《PythonWeb框架Flask、Streamlit、FastAPI示例详解》本文对比分析了Flask、Streamlit和FastAPI三大PythonWeb框架:Flask轻量灵活适合传统应用... 目录概述Flask详解Flask简介安装和基础配置核心概念路由和视图模板系统数据库集成实际示例Stre

如何在Java Spring实现异步执行(详细篇)

《如何在JavaSpring实现异步执行(详细篇)》Spring框架通过@Async、Executor等实现异步执行,提升系统性能与响应速度,支持自定义线程池管理并发,本文给大家介绍如何在Sprin... 目录前言1. 使用 @Async 实现异步执行1.1 启用异步执行支持1.2 创建异步方法1.3 调用

Spring Boot3.0新特性全面解析与应用实战

《SpringBoot3.0新特性全面解析与应用实战》SpringBoot3.0作为Spring生态系统的一个重要里程碑,带来了众多令人兴奋的新特性和改进,本文将深入解析SpringBoot3.0的... 目录核心变化概览Java版本要求提升迁移至Jakarta EE重要新特性详解1. Native Ima