在Golang的go-colly中如何限制第三方URL访问?

在Golang的go-colly中如何限制第三方URL访问? 我需要爬取类似 abc.com 这样的域名,但在访问过程中会重定向到许多第三方网址,比如 facebook.comgoogle.com 等。

Go Colly 是否有类似 Scrapy LinkExtractor 规则的域名限制规则?

3 回复

colly.Collector 有一个 AllowedDomains 字段。尝试设置这个字段。

// Collector 提供用于抓取任务的爬虫实例
type Collector struct {
	// UserAgent 是 HTTP 请求使用的 User-Agent 字符串
	UserAgent string
	// MaxDepth 限制访问 URL 的递归深度
	// 设置为 0 表示无限递归(默认值)
	MaxDepth int
	// AllowedDomains 是域名白名单
	// 留空则允许访问任何域名
	AllowedDomains []string
	// DisallowedDomains 是域名黑名单

更多关于在Golang的go-colly中如何限制第三方URL访问?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


此外,收集器中的 RedirectHandler 也可以使用

github.com

gocolly/colly/blob/master/colly.go#L105

	Async bool
	// ParseHTTPErrorResponse 允许解析状态码非2xx的HTTP响应
	// 默认情况下,Colly仅解析成功的HTTP响应。将ParseHTTPErrorResponse
	// 设置为true以启用此功能
	ParseHTTPErrorResponse bool
	// ID 是收集器的唯一标识符
	ID uint32
	// DetectCharset 可以为没有显式字符集声明的非utf8响应体启用字符编码检测
	// 此功能使用 https://github.com/saintfish/chardet
	DetectCharset bool
	// RedirectHandler 允许控制重定向的处理方式
	RedirectHandler   func(req *http.Request, via []*http.Request) error
	store             storage.Storage
	debugger          debug.Debugger
	robotsMap         map[string]*robotstxt.RobotsData
	htmlCallbacks     []*htmlCallbackContainer
	xmlCallbacks      []*xmlCallbackContainer
	requestCallbacks  []RequestCallback
	responseCallbacks []ResponseCallback
	errorCallbacks    []ErrorCallback
	scrapedCallbacks  []ScrapedCallback

在Go Colly中,可以通过设置AllowedDomains来限制爬虫只访问特定域名。以下是一个完整的示例代码:

package main

import (
    "fmt"
    "github.com/gocolly/colly"
)

func main() {
    c := colly.NewCollector(
        // 设置允许访问的域名白名单
        colly.AllowedDomains("abc.com", "www.abc.com"),
    )

    // 处理重定向
    c.SetRedirectHandler(func(req *colly.Request, via []*colly.Request) error {
        // 检查重定向URL是否在允许的域名内
        if !c.Allowed(req.URL.Host) {
            fmt.Printf("阻止重定向到第三方域名: %s\n", req.URL.String())
            return fmt.Errorf("禁止访问第三方域名")
        }
        return nil
    })

    // 找到链接时的回调
    c.OnHTML("a[href]", func(e *colly.HTMLElement) {
        link := e.Attr("href")
        fmt.Printf("发现链接: %s\n", link)
        e.Request.Visit(link)
    })

    // 请求错误处理
    c.OnError(func(r *colly.Response, err error) {
        fmt.Printf("请求错误: %v\n", err)
    })

    // 开始爬取
    err := c.Visit("http://abc.com")
    if err != nil {
        fmt.Printf("访问失败: %v\n", err)
    }
}

如果需要更细粒度的控制,还可以使用URLFilters

c := colly.NewCollector()

// 自定义URL过滤函数
c.URLFilters = []*colly.URLFilter{
    colly.NewURLFilter("abc\\.com"),
}

// 或者使用正则表达式过滤
c.AllowedDomains = []string{"abc.com", "sub.abc.com"}

这样配置后,爬虫只会访问abc.com及其子域名下的链接,任何重定向到facebook.comgoogle.com等第三方域名的请求都会被自动阻止。

回到顶部