safescrape

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 5 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

safescrape

safescrape は、Webスクレイピングを安全に行うためのシンプルなGo言語用パッケージです。 指定されたURIへアクセスする前に、対象ドメインの robots.txt を自動的に取得・解析し、指定したユーザーエージェントによるアクセスが許可されているかを確認します。アクセスが拒否されている場合は safescrape.ErrRobots エラーを返し、安全かつマナーを守ったスクレイピングを実現します。

特徴

  • 実際のページへアクセスする前に自動で robots.txt の内容をチェック
  • context.Context をサポートし、タイムアウトやキャンセル処理に対応
  • シンプルで使いやすいインターフェース

インストール

go get コマンドを使用してプロジェクトにインストールします。

go get github.com/j-sato-t/safescrape

使い方

以下の例は、safescrape.Scrape 関数を使用して安全に Web ページの内容を取得する方法を示しています。

package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"time"

	"github.com/j-sato-t/safescrape"
)

func main() {
	// タイムアウト付きのコンテキストを作成
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// アクセスするURLと使用するユーザーエージェント
	uri := "https://example.com"
	ua := "MyCustomScraper/1.0"

	// スクレイピングを実行
	resp, err := safescrape.Scrape(ctx, uri, ua)
	if err != nil {
		if err == safescrape.ErrRobots {
			log.Fatalf("アクセスは robots.txt によって拒否されました: %v", err)
			return
		}
		log.Fatalf("エラーが発生しました: %v", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("レスポンスボディの読み込みに失敗しました: %v", err)
	}

	fmt.Printf("ステータスコード: %d, 取得コンテンツ: %d バイト\n", resp.StatusCode, len(body))
}

ベストプラクティス

スクレイピングを行う際は、アクセス先のサーバー管理者があなたに連絡を取れるよう、ユーザーエージェント(User-Agent)に連絡先(メールアドレスやWebサイトのURLなど)を含めることを強く推奨します。これにより、アクセス過多など予期せぬ問題が発生した際に円滑な対応が可能になります。

例:

ua := "MyCustomScraper/1.0 (+https://example.com/bot; contact@example.com)"

免責事項

本パッケージは robots.txt を自動で確認することで行儀の良いスクレイピングを支援するものですが、アクセス先の利用規約の遵守や、相手サーバーに過度な負荷をかけないことを完全に保証するものではありません。 本パッケージを利用したことによって生じた対象サイトとのトラブルや損害等について、開発者は一切の責任を負いかねます。ご自身の責任においてご利用ください。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrRobots = errors.New("access denied by robots.txt")

ErrRobots は robots.txt によってアクセスが拒否されたことを示します。

Functions

func Scrape

func Scrape(ctx context.Context, uri string, ua string) (*http.Response, error)

Scrape は指定された URI にアクセスしてその結果を返します。 アクセス前に robots.txt を確認し、拒否される場合は ErrRobots を返します。

Types

This section is empty.

Jump to

Keyboard shortcuts

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