imagecapture

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 26, 2025 License: Apache-2.0 Imports: 24 Imported by: 0

README

imagecapture - 图片抓取 工具

ChopperBot

图片捕获器

简体中文文档 github stars github stars

imagecapture ImageCapture 是一个用 Go 语言编写的库,旨在从百度和必应等搜索引擎捕获图片。它提供了一个接口,用于搜索和下载图片,并支持多种自定义选项。

特性

  • 多引擎支持:支持百度、必应,后续将添加 Google 搜索。
  • 高级筛选:支持根据版权、图片尺寸、动图等进行筛选。
  • 并发抓取:使用并发抓取功能,提高图片抓取效率。
  • 去重功能:自动去重,确保返回的图片 URL 唯一。
  • 分页迭代功能:- 支持大批量图片的分页获取。。

安装

通过 go get 安装该工具包:

go get github.com/code-innovator-zyx/imagecapture

快速开始

初始化 BaiduCapture
package main

import (
	"fmt"
	"github.com/code-innovator-zyx/imagecapture"
	"log"
)

func main() {
	keyword := "美女"
	maxImageNums := 20
	// 新建一个百度图片捕获器  routineSize 限制协爬取的携程池数量
	baiduCapture := imagecapture.NewBaiduCapture(5)
	// 搜索图片
	urls, err := baiduCapture.SearchImages(keyword, maxImageNums)
	if err != nil {
		log.Fatalln(err.Error())
	}
	filename := "./beautiful"
	// 可以使用内置下载器下载图片   注:文件后缀会根据图片真是类型进行判断
	suffix, err := baiduCapture.Download(urls[0], filename, nil)
	if err != nil {
		log.Fatalln(err.Error())
	}
	fmt.Println(suffix)
}

初始化 BingCapture
package main

import (
	"fmt"
	"github.com/code-innovator-zyx/imagecapture"
	"log"
)

func main() {
	keyword := "美女"
	maxImageNums := 20
	// 新建一个必应图片捕获器  routineSize 限制协爬取的携程池数量
	bingCapture := imagecapture.NewBingCapture(5)
	// 搜索图片
	urls, err := bingCapture.SearchImages(keyword, maxImageNums)
	if err != nil {
		log.Fatalln(err.Error())
	}
	filename := "./beautiful"
	// 可以使用内置下载器下载图片   注:文件后缀会根据图片真是类型进行判断
	suffix, err := bingCapture.Download(urls[0], filename, nil)
	if err != nil {
		log.Fatalln(err.Error())
	}
	fmt.Println(suffix)
}

主要功能

SearchImages

用于在指定搜索引擎中根据关键词搜索图片。

参数
  • keyword (string): 搜索关键词。
  • maxNumber (int): 要返回的最多图片数量。
  • opts (Option): 可选参数,用于指定其他筛选条件(例如图片尺寸、是否高清、动图等)。
示例
// 使用 WithImageSize、WithHd 等选项来进行筛选
images, err := baiduCapture.SearchImages("sunrise", 20, imagecapture.WithHd(), imagecapture.WithImageSize(imagecapture.Medium))

RangeImages

用于在指定搜索引擎中根据关键词持续搜索图片。

参数
  • keyword (string): 搜索关键词。
  • callBack (func(string)bool): 每一批图片的回调函数。
  • opts (Option): 可选参数,用于指定其他筛选条件(例如图片尺寸、是否高清、动图等)。
示例
capture.RangeImages("老虎", func (urls []string) bool {
return true
})
if err != nil {
t.Error(err.Error())
return
}
})

更多案例

支持的筛选选项

仅百度搜索支持以下筛选选项:
1. WithCopyright()

过滤版权问题的图片,仅返回无版权限制的图片。

2. WithImageSize(size ImageSize)

限制搜索图片的大小。ImageSize 可以是以下几种:

  • Small:小尺寸
  • Medium:中等尺寸
  • Large:大尺寸
3. WithLatest()

搜索最新的图片,仅返回最近上传或更新的图片。

4. WithGif()

搜索动图,返回 .gif 格式的图片。

5. WithHd()

搜索高清图

图片去重

工具 内部会使用 map 来去重 URL,确保每个返回的 URL 唯一。这样可以避免重复图片 URL 出现在结果中。

配置

配置并发度

BaiduCaptureBingCapture 都可以通过传入并发数量来配置并发度,最多支持 6 个并发。

bingCapture := imagecapture.NewBaiduCapture(6) // 最大并发6

免责声明

本项目仅用于个人学习、研究和开发目的,禁止用于任何非法用途或商业用途。使用本 库 进行的所有操作和行为由用户自行承担风险。

  • 本 库 的图片抓取功能仅适用于合法的数据抓取用途,用户应遵守相关法律法规。
  • 本 库 使用的第三方图片搜索引擎(如百度、必应等)可能会随时更改其接口或数据访问策略,使用时需自行留意相关的变化。
  • 本项目不对通过 库 抓取的任何内容的版权、合法性等问题承担任何责任。

使用本库即表示用户同意并遵守上述条款。

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDownloadFailed   = errors.New("failed to download image")        // 下载失败
	ErrMaxRetryExceeded = errors.New("maximum retry attempts exceeded") // 达到最大重试次数
	// 网络连接或URL相关错误
	ErrInvalidURL       = errors.New("invalid URL")        // URL格式不正确
	ErrConnectionFailed = errors.New("connection failed")  // 网络连接失败
	ErrTimeout          = errors.New("connection timeout") // 连接超时
	ErrHostUnreachable  = errors.New("host unreachable")   // 无法访问主机

	// 文件操作相关错误
	ErrFileCreationFailed    = errors.New("file creation failed")    // 创建文件失败
	ErrFileWriteFailed       = errors.New("file write failed")       // 文件写入失败
	ErrFilePermissionDenied  = errors.New("file permission denied")  // 文件权限不足
	ErrDiskSpaceInsufficient = errors.New("insufficient disk space") // 磁盘空间不足

	// 数据读取与解码相关错误
	ErrReadFailed         = errors.New("failed to read data from source") // 数据读取失败
	ErrDataDecodingFailed = errors.New("failed to decode data")           // 数据解码失败

	// 目标路径相关错误
	ErrInvalidTargetPath    = errors.New("invalid target path")           // 目标路径不正确
	ErrDirectoryNotWritable = errors.New("target directory not writable") // 目标目录无法写入
	ErrFileAlreadyExists    = errors.New("file already exists")           // 文件已存在

	// 下载内容相关错误
	ErrUnsupportedFileType     = errors.New("unsupported file type")      // 文件类型不支持
	ErrContentTooLarge         = errors.New("content size exceeds limit") // 内容大小超过限制
	ErrContentChecksumMismatch = errors.New("content checksum mismatch")  // 校验和不匹配,可能数据损坏
)

* @Author: zouyx * @Email: 1003941268@qq.com * @Date: 2024/11/4 上午10:48 * @Package:

View Source
var (
	//  抖音源
	RULE_DOUYIN = Rule{
		"douyin.com",
		"douyinpic.com",
		"ixigua.com",
		"snssdk.com",
		"amemv.com",
		"tiktok.com",
	}
	// 新浪源
	RULES_SINA = Rule{
		"sinaimg.cn",
		"sinajs.cn",
		"sina.com.cn",
		"vip.sina.com",
	}
)

Functions

func GenerateUUID

func GenerateUUID() (string, error)

GenerateUUID 生成uuid

func Max

func Max[T Element](x, y T) T

func Min

func Min[T Element](x, y T) T

func NewGoogleCapture

func NewGoogleCapture()

Types

type BaiduCapture

type BaiduCapture struct {
	Downloader
	// contains filtered or unexported fields
}

BaiduCapture 实现百度图片搜索引擎

func (*BaiduCapture) RangeImages

func (bc *BaiduCapture) RangeImages(keyword string, callBack func([]string) bool, opts ...Option) error

func (*BaiduCapture) SearchImages

func (bc *BaiduCapture) SearchImages(keyword string, maxNumber int, opts ...Option) ([]string, error)

type BingCapture

type BingCapture struct {
	Downloader
	// contains filtered or unexported fields
}

func (*BingCapture) RangeImages

func (bc *BingCapture) RangeImages(keyword string, callBack func([]string) bool, opts ...Option) error

func (*BingCapture) SearchImages

func (bc *BingCapture) SearchImages(keyword string, maxNumber int, opts ...Option) ([]string, error)

type BingFormat

type BingFormat struct {
	Murl string `json:"murl"`
	Turl string `json:"turl"`
}

type BloomFilter added in v1.0.2

type BloomFilter struct {
	// contains filtered or unexported fields
}

func NewBloomFilter added in v1.0.2

func NewBloomFilter(expectedItems uint, falsePositiveRate float64) *BloomFilter

func (*BloomFilter) Add added in v1.0.2

func (bf *BloomFilter) Add(item string)

func (*BloomFilter) Contains added in v1.0.2

func (bf *BloomFilter) Contains(item string) bool

type Cache added in v1.0.2

type Cache struct {
	// contains filtered or unexported fields
}

func NewCache added in v1.0.2

func NewCache(maxSize int, lifetime time.Duration) *Cache

func (*Cache) Clear added in v1.0.2

func (c *Cache) Clear()

func (*Cache) Get added in v1.0.2

func (c *Cache) Get(key string) (interface{}, bool)

func (*Cache) Set added in v1.0.2

func (c *Cache) Set(key string, value interface{})

type Capture

type Capture interface {
	Downloader
	/**
	搜索图片: 注 【对图片去重后返回的图片是无序的】
	@param keywords: 搜索关键词
	@param maxNumber: 最多返回的图片数量
	@param opts: 额外参数,支持多种选项
	@return: 返回图片 URL 列表和可能的错误
	*/
	SearchImages(keyword string, maxNumber int, opts ...Option) ([]string, error)

	/**
	分页范围图片搜索:用于分批获取搜索结果
	@param keyword: 搜索关键词
	@param callBack: 回调函数,用于处理返回的每一批次图片 URL 列表的函数。如果 `fn` 返回 `false`,则停止后续搜索
	@param opts: 额外参数,支持多种选项
	@return: 返回当前页码的图片 URL 列表和可能的错误
	*/
	RangeImages(keyword string, callBack func(urls []string) bool, opts ...Option) error
}

* @Author: zouyx * @Email:1003941268@qq.com * @Date: 2024/11/1 下午6:25 * @Package:

func NewBaiduCapture

func NewBaiduCapture(routineSize int) Capture

NewBaiduCapture 初始化百度图片搜索引擎 传入最大支持并发数量,建议不超过6个

func NewBingCapture

func NewBingCapture(routineSize int) Capture

type Downloader

type Downloader interface {
	// 下载图片到指定文件路径。如果 writer 不为 nil,将数据写入 writer;否则保存到 filename 文件中。
	// @param url: 图片 URL
	// @param filename: 保存的文件名
	// @param writer: 可选的 io.Writer 用于写入数据
	// @return: 下载成功返回文件名后缀  eg:[png],返回可能的错误
	Download(url, filename string, writer io.Writer) (string, error)
	//// 批量下载所有图片到指定目录,是否以图片的 MD5 值命名,返回已下载成功的文件路径。
	//// @param urls: 图片 URL 列表
	//// @param dir: 保存目录
	//// @param useMd5Naming: 是否使用 MD5 值命名
	//// @return: 返回已成功下载的文件路径列表和可能的错误
	BatchDownload(urls []string, dir string, useMd5Naming bool) ([]string, error)
}

type Element

type Element interface {
	~int | ~string | ~float64 | ~float32
}

type GoogleCapture

type GoogleCapture struct{}

func (GoogleCapture) BatchDownload

func (GoogleCapture) BatchDownload(urls []string, dir string, useMd5Naming bool) ([]string, error)

func (GoogleCapture) Download

func (GoogleCapture) Download(url, filename string, writer io.Writer) error

func (GoogleCapture) SearchImages

func (GoogleCapture) SearchImages(keywords string, maxNumber int, opts ...Option) ([]string, error)

type ImageReader

type ImageReader struct {
	io.Reader
	// contains filtered or unexported fields
}

func NewImageReader

func NewImageReader(reader io.Reader, needMd5 bool) (*ImageReader, error)

func (ImageReader) Md5

func (ir ImageReader) Md5() string

func (ImageReader) Read

func (ir ImageReader) Read(p []byte) (n int, err error)

func (ImageReader) Type

func (ir ImageReader) Type() string

type ImageSize

type ImageSize uint

需要搜索的图片大小

const (
	ImageSize_SMALL  ImageSize // 小图
	ImageSize_MEDIUM           // 中图
	ImageSize_LARGE            // 大图

	ImageSize_ENORMOUS // 特大图片
)

type Option

type Option func(*query)

func WithCopyright

func WithCopyright() Option

WithCopyright 过滤版权数据

func WithGif

func WithGif() Option

WithGif 搜索动图

func WithHd

func WithHd() Option

WithHd 搜素高清图

func WithImageSize

func WithImageSize(size ImageSize) Option

WithImageSize 搜索的图片大小限制

func WithLatest

func WithLatest() Option

WithLatest 搜索最新图片

type Rule added in v1.0.1

type Rule []string

func (Rule) Check added in v1.0.1

func (r Rule) Check(rawURL string) bool

规则校验

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL