インターネットを使って情報をやり取りするには、必ずIPアドレスが必要です。WebサイトはこのIPアドレスを使用してユーザーを識別し、ユーザーの位置情報やその他のメタデータ(ISP、タイムゾーン、デバイスタイプなど)を特定します。Webサーバーはこれらの情報を利用して、コンテンツやリソースを調整したり制限したりできます。つまり、Webサイトは、Webスクレイピング時のトラフィックパターンや動作に何らかの異常性、ボットの特性、あるいは悪意があると判断した場合、そのIPアドレスから送信されたリクエストをブロックできるのです。この問題を解決するのがプロキシサーバーです。
プロキシサーバーとは、ユーザーとインターネットの中間にあってゲートウェイとして機能するサーバーのことで、ユーザーからリクエストを受け取ってWebリソースに転送し、取得したデータをユーザーに返します。プロキシサーバーによって発信元のIPアドレスが隠され、セキュリティ、プライバシー、匿名性が高まるので、閲覧やスクレイピングを慎重に行うことができます。
プロキシサーバーには、IPアドレスを適宜変更して、リクエストがさまざまなユーザーから来ているように見せかける機能があり、IPバン(接続禁止)を回避するのにも役立ちます。さまざまな地域にあるプロキシサーバーを使用すれば、ジオブロッキングを迂回して、映画やニュースなど地域固有のコンテンツにアクセスできます。
この記事では、GoでWebスクレイピング用のプロキシサーバーをセットアップする方法について説明します。Bright Dataプロキシサーバーでこのプロセスをどのように簡素化できるかについてもお分かりいただけるでしょう。
プロキシサーバーをセットアップする
このチュートリアルでは、Goで記述されたWebスクレイパーアプリケーションを変更して、ローカルまたはセルフホストのプロキシサーバー経由でIt’s FOSSのWebサイトとやり取りするまでを学習します。Go開発環境はセットアップ済みであることが前提です。
最初に、オープンソースのプロキシサーバーソフトウェアSquidを使用してプロキシサーバーをセットアップする必要があります。使い慣れているプロキシサーバーソフトウェアが他にあるなら、それを使ってもかまいません。次の記事では、Fedora 39 LinuxマシンでSquidを使用します。Squidは、ほとんどのLinuxディストリビューションのデフォルトリポジトリに含まれています。マニュアルを参照して、お使いのオペレーティングシステムに必要なパッケージをダウンロードすることもできます。
端末から次のコマンドを実行してSquidをインストールします。
dnf install squid -yn
完了したら、次のコマンドを実行してサービスを開始します。
sudo systemctl enable u002du002dnow squidn
次のコマンドを使用してサービスのステータスを確認してください。
sudo systemctl status squidn
出力は次のようになります。

これは、サービスが有効で実行中であることを示します。デフォルトでは、Squidはポート3128で実行され、リクエストを受け取ります。次のcurlコマンドを使用して、プロキシサーバー経由の通信をテストしてください。
curl u002du002dproxy 127.0.0.1:3128 u0022http://lumtest.com/myip.jsonu0022n
次のような応答が返ってくればOKです。
curl u002du002dproxy 127.0.0.1:3128 u0022http://lumtest.com/myip.jsonu0022n{u0022ipu0022:u0022196.43.196.126u0022,u0022countryu0022:u0022GHu0022,u0022asnu0022:{u0022asnumu0022:327695,u0022org_nameu0022:u0022AITIu0022},u0022geou0022:{u0022cityu0022:u0022u0022,u0022regionu0022:u0022u0022,u0022region_nameu0022:u0022u0022,u0022postal_codeu0022:u0022u0022,u0022latitudeu0022:8.1,u0022longitudeu0022:-1.2,u0022tzu0022:u0022Africa/Accrau0022}}nn
メタデータにはパブリックIPアドレス、および所有者の国と組織が含まれているので、正常に動作するプロキシサーバーがインストールされていることも確認できました。
デモ用スクレイパーをセットアップする
わかりやすくするために、このGitHubリポジトリにあるシンプルなGo Webスクレイパーアプリケーションを使います。このスクレイパーは、オープンソースソフトウェア製品について話し合う人気ブログIt’s FOSSの最新の投稿のタイトル、抜粋、カテゴリを取り込みます。次に、スクレイパーはLumtestにアクセスして、スクレイパーのHTTPクライアントがWebとのやり取りに使用するIPアドレスに関する情報を取得します。Colly、goquery、Seleniumという異なる3つのGoパッケージで同じロジックが実装されます。次のセクションでは、プロキシサーバーを使用するように各実装を変更する方法について説明します。
最初に、お気に入りの端末/シェルで次のコマンドを実行して、リポジトリを複製します。
$ git clone https://github.com/rexfordnyrk/go_scrap_proxy.gitn
このリポジトリは、完成したコードを含むメイン
ブランチと、変更対象の初期コードを含むbasic
ブランチの2つのブランチで構成されています。次のコマンドを使って、basic
ブランチにチェックアウト
します。
$ git checkout basicn
このブランチでは、プロキシが設定されていないスクレイパーのライブラリ実装ごとに3つの.go
ファイルが含まれています。実行ファイルchromedriver
も含まれていますが、これはスクレイパーのSelenium実装に必要です。
.nâââ chromedrivernâââ colly.gonâââ go.modnâââ goquery.gonâââ go.sumnâââ LICENSEnâââ README.mdnâââ selenium.gonn1 directory, 8 filesn
特定のファイル名でgo run
コマンドを使用すると、どの実装も個別に実行できます。たとえば、次のコマンドはCollyでスクレイパーを実行します。
go run ./colly.go n
出力は次のようになります。
$ go run ./colly.gonnArticle 0: {u0022categoryu0022:u0022Newsletter âï¸u0022,u0022excerptu0022:u0022Unwind your new year celebration with new open-source projects, and keep an eye on interesting distro updates.u0022,u0022titleu0022:u0022FOSS Weekly #24.02: Mixing AI With Linux, Vanilla OS 2, and Moreu0022}nArticle 1: {u0022categoryu0022:u0022Tutorialu0022,u0022excerptu0022:u0022Wondering how to use tiling windows on GNOME? Try the tiling assistant. Here's how it works.u0022,u0022titleu0022:u0022How to Use Tiling Assistant on GNOME Desktop?u0022}nArticle 2: {u0022categoryu0022:u0022Linux Commandsu0022,u0022excerptu0022:u0022The free command in Linux helps you gain insights on system memory usage (RAM), and more. Here's how to make good use of it.u0022,u0022titleu0022:u0022Free Command Examplesu0022}nArticle 3: {u0022categoryu0022:u0022Gaming ð®u0022,u0022excerptu0022:u0022Here are the best tips to make your Linux gaming experience enjoyable.u0022,u0022titleu0022:u00227 Tips and Tools to Improve Your Gaming Experience on Linuxu0022}nArticle 4: {u0022categoryu0022:u0022Newsletter âï¸u0022,u0022excerptu0022:u0022The first edition of FOSS Weekly in the year 2024 is here. See, what's new in the new year.u0022,u0022titleu0022:u0022FOSS Weekly #24.01: Linux in 2024, GDM Customization, Distros You Missed Last Yearu0022}nArticle 5: {u0022categoryu0022:u0022Tutorialu0022,u0022excerptu0022:u0022Wondering which init service your Linux system uses? Here's how to find it out.u0022,u0022titleu0022:u0022How to Check if Your Linux System Uses systemdu0022}nArticle 6: {u0022categoryu0022:u0022Ubuntuu0022,u0022excerptu0022:u0022Learn the logic behind each step you have to follow for adding an external repository in Ubuntu and installing packages from it.u0022,u0022titleu0022:u0022Installing Packages From External Repositories in Ubuntu [Explained]u0022}nArticle 7: {u0022categoryu0022:u0022Troubleshoot ð¬u0022,u0022excerptu0022:u0022Getting a warning that the boot partition has no space left? Here are some ways you can free up space on the boot partition in Ubuntu Linux.u0022,u0022titleu0022:u0022How to Free Up Space in /boot Partition on Ubuntu Linux?u0022}nArticle 8: {u0022categoryu0022:u0022Ubuntuu0022,u0022excerptu0022:u0022Wondering which Ubuntu version you're using? Here's how to check your Ubuntu version, desktop environment and other relevant system information.u0022,u0022titleu0022:u0022How to Check Ubuntu Version Details and Other System Informationu0022}nnCheck Proxy IP map[asn:map[asnum:29614 org_name:VODAFONE GHANA AS INTERNATIONAL TRANSIT] country:GH geo:map[city:Accra latitude:5.5486 longitude:-0.2012 lum_city:accra lum_region:aa postal_code: region:AA region_name:Greater Accra Region tz:Africa/Accra] ip:197.251.144.148]n
It’s FOSSからスクレイピングされた記事情報がすべて出力されます。出力の最後には、スクレイパーが使用している現在の接続について、Lumtestから返されたIP情報が表示されます。3つの実装すべてで、同様の実行結果が得られるはずです。3つのテストがすべて完了したら、ローカルプロキシを使ったスクレイピングをすぐに開始できます。
ローカルプロキシを使うスクレイパーを実装する
このセクションでは、スクレイパーの3つの実装について説明し、各スクレイパーでプロキシサーバーを使用するように変更していきます。各.go
ファイルは、アプリケーションを起動するmain()
関数と、スクレイピングの指示が記述されているScrapeWithLibrary()
関数で構成されています。
goqueryでローカルプロキシを使う
goqueryはGo用のライブラリで、JavaScriptに対するjQueryの働きと同様に、HTMLドキュメントを解析して操作するための一連のメソッドと機能を提供します。このライブラリは、HTMLページの構造をトラバース、クエリ、操作できるのでWebスクレイピングに特に役立ちますが、ネットワークに対するリクエストや操作を一切行わないため、HTMLページを取得して提供する責任は呼び出し側にあります。
goquery.go
ファイルに移動して、Webスクレイパーのgoquery実装を確認できます。使い慣れたIDEやテキストエディタで開いてください。
ScrapeWithGoQuery()
関数内で、HTTPクライアントのトランスポートをHTTPプロキシサーバーのURLで変更する必要があります。URL は、http://HOST:PORT
という形式のホスト名またはIPとポートの組み合わせです。
このファイルにnet/url
パッケージを必ずインポートしてください。HTTPクライアント定義を貼り付けて、次のスニペットに置き換えます。
...nnfunc ScrapeWithGoquery() {n // Define the URL of the proxy servern proxyStr := u0022http://127.0.0.1:3128u0022nn // Parse the proxy URLn proxyURL, err := url.Parse(proxyStr)n if err != nil {n fmt.Println(u0022Error parsing proxy URL:u0022, err)n returnn }nn //Create an http.Transport that uses the proxyn transport := u0026http.Transport{n Proxy: http.ProxyURL(proxyURL),n }nn // Create an HTTP client with the transportn client := u0026http.Client{n Transport: transport,n }n n... n
このスニペットは、ローカルプロキシサーバーを使用するように設定されたトランスポートでHTTPクライアントを変更します。IPアドレスは必ずプロキシサーバーのIPアドレスに置き換えてください。
次に、プロジェクトディレクトリから次のコマンドを使用してこの実装を実行します。
go run ./goquery.gon
出力は次のようになります。
$ go run ./goquery.gonnArticle 0: {u0022categoryu0022:u0022Newsletter âï¸u0022,u0022excerptu0022:u0022Unwind your new year celebration with new open-source projects, and keep an eye on interesting distro updates.u0022,u0022titleu0022:u0022FOSS Weekly #24.02: Mixing AI With Linux, Vanilla OS 2, and Moreu0022}nArticle 1: {u0022categoryu0022:u0022Tutorialu0022,u0022excerptu0022:u0022Wondering how to use tiling windows on GNOME? Try the tiling assistant. Here's how it works.u0022,u0022titleu0022:u0022How to Use Tiling Assistant on GNOME Desktop?u0022}nArticle 2: {u0022categoryu0022:u0022Linux Commandsu0022,u0022excerptu0022:u0022The free command in Linux helps you gain insights on system memory usage (RAM), and more. Here's how to make good use of it.u0022,u0022titleu0022:u0022Free Command Examplesu0022}nArticle 3: {u0022categoryu0022:u0022Gaming ð®u0022,u0022excerptu0022:u0022Here are the best tips to make your Linux gaming experience enjoyable.u0022,u0022titleu0022:u00227 Tips and Tools to Improve Your Gaming Experience on Linuxu0022}nArticle 4: {u0022categoryu0022:u0022Newsletter âï¸u0022,u0022excerptu0022:u0022The first edition of FOSS Weekly in the year 2024 is here. See, what's new in the new year.u0022,u0022titleu0022:u0022FOSS Weekly #24.01: Linux in 2024, GDM Customization, Distros You Missed Last Yearu0022}nArticle 5: {u0022categoryu0022:u0022Tutorialu0022,u0022excerptu0022:u0022Wondering which init service your Linux system uses? Here's how to find it out.u0022,u0022titleu0022:u0022How to Check if Your Linux System Uses systemdu0022}nArticle 6: {u0022categoryu0022:u0022Ubuntuu0022,u0022excerptu0022:u0022Learn the logic behind each step you have to follow for adding an external repository in Ubuntu and installing packages from it.u0022,u0022titleu0022:u0022Installing Packages From External Repositories in Ubuntu [Explained]u0022}nArticle 7: {u0022categoryu0022:u0022Troubleshoot ð¬u0022,u0022excerptu0022:u0022Getting a warning that the boot partition has no space left? Here are some ways you can free up space on the boot partition in Ubuntu Linux.u0022,u0022titleu0022:u0022How to Free Up Space in /boot Partition on Ubuntu Linux?u0022}nArticle 8: {u0022categoryu0022:u0022Ubuntuu0022,u0022excerptu0022:u0022Wondering which Ubuntu version you're using? Here's how to check your Ubuntu version, desktop environment and other relevant system information.u0022,u0022titleu0022:u0022How to Check Ubuntu Version Details and Other System Informationu0022}nnCheck Proxy IP map[asn:map[asnum:29614 org_name:VODAFONE GHANA AS INTERNATIONAL TRANSIT] country:GH geo:map[city:Accra latitude:5.5486 longitude:-0.2012 lum_city:accra lum_region:aa postal_code: region:AA region_name:Greater Accra Region tz:Africa/Accra] ip:197.251.144.148]n
Collyでローカルプロキシを使う
CollyはGo用の多用途で効率的なWebスクレイピングフレームワークで、使いやすいAPIや、goquery
などのHTML解析ライブラリとシームレスに統合できることが特長です。goquery
とは異なり、高速スクレイピング、ローカルキャッシュ、レート制限の非同期リクエストなど、ネットワーク関連のさまざまな動作を処理するためのAPIをサポートおよび提供します。これによって、Webリソースの効率的かつ責任ある使用、Cookieとセッションの自動処理、カスタマイズ可能なユーザーエージェント、包括的なエラー処理が保証されます。プロキシの切り替えやローテーションを行いながらプロキシを使用することもできます。ヘッドレスブラウザーと統合すれば、JavaScriptで生成されたコンテンツのスクレイピングなどのタスクにも拡張できます。
colly.go
ファイルをエディタかIDEで開き、ScrapeWithColly()
関数内で新しいコレクタを初期化した直後に、次のコードを貼り付けてください。
...n // Define the URL of the proxy servern proxyStr := u0022http://127.0.0.1:3128u0022n // SetProxy sets a proxy for the collectorn if err := c.SetProxy(proxyStr); err != nil {n log.Fatalf(u0022Error setting proxy configuration: %vu0022, err)n }n n...n
このスニペットはCollyのsetProxy()
メソッドを使用して、このコレクタインスタンスでネットワークリクエストに使用されるプロキシサーバーを定義します。
次に、プロジェクトディレクトリから次のコマンドを使用してこの実装を実行します。
go run ./colly.gon
出力は次のようになります。
$ go run ./colly.gonnArticle 0: {u0022categoryu0022:u0022Newsletter âï¸u0022,u0022excerptu0022:u0022Unwind your new year celebration with new open-source projects, and keep an eye on interesting distro updates.u0022,u0022titleu0022:u0022FOSS Weekly #24.02: Mixing AI With Linux, Vanilla OS 2, and Moreu0022}nArticle 1: {u0022categoryu0022:u0022Tutorialu0022,u0022excerptu0022:u0022Wondering how to use tiling windows on GNOME? Try the tiling assistant. Here's how it works.u0022,u0022titleu0022:u0022How to Use Tiling Assistant on GNOME Desktop?u0022}nArticle 2: {u0022categoryu0022:u0022Linux Commandsu0022,u0022excerptu0022:u0022The free command in Linux helps you gain insights on system memory usage (RAM), and more. Here's how to make good use of it.u0022,u0022titleu0022:u0022Free Command Examplesu0022}nArticle 3: {u0022categoryu0022:u0022Gaming ð®u0022,u0022excerptu0022:u0022Here are the best tips to make your Linux gaming experience enjoyable.u0022,u0022titleu0022:u00227 Tips and Tools to Improve Your Gaming Experience on Linuxu0022}nArticle 4: {u0022categoryu0022:u0022Newsletter âï¸u0022,u0022excerptu0022:u0022The first edition of FOSS Weekly in the year 2024 is here. See, what's new in the new year.u0022,u0022titleu0022:u0022FOSS Weekly #24.01: Linux in 2024, GDM Customization, Distros You Missed Last Yearu0022}nArticle 5: {u0022categoryu0022:u0022Tutorialu0022,u0022excerptu0022:u0022Wondering which init service your Linux system uses? Here's how to find it out.u0022,u0022titleu0022:u0022How to Check if Your Linux System Uses systemdu0022}nArticle 6: {u0022categoryu0022:u0022Ubuntuu0022,u0022excerptu0022:u0022Learn the logic behind each step you have to follow for adding an external repository in Ubuntu and installing packages from it.u0022,u0022titleu0022:u0022Installing Packages From External Repositories in Ubuntu [Explained]u0022}nArticle 7: {u0022categoryu0022:u0022Troubleshoot ð¬u0022,u0022excerptu0022:u0022Getting a warning that the boot partition has no space left? Here are some ways you can free up space on the boot partition in Ubuntu Linux.u0022,u0022titleu0022:u0022How to Free Up Space in /boot Partition on Ubuntu Linux?u0022}nArticle 8: {u0022categoryu0022:u0022Ubuntuu0022,u0022excerptu0022:u0022Wondering which Ubuntu version you're using? Here's how to check your Ubuntu version, desktop environment and other relevant system information.u0022,u0022titleu0022:u0022How to Check Ubuntu Version Details and Other System Informationu0022}nnCheck Proxy IP map[asn:map[asnum:29614 org_name:VODAFONE GHANA AS INTERNATIONAL TRANSIT] country:GH geo:map[city:Accra latitude:5.5486 longitude:-0.2012 lum_city:accra lum_region:aa postal_code: region:AA region_name:Greater Accra Region tz:Africa/Accra] ip:197.251.144.148]nn
Seleniumでローカルプロキシを使う
Seleniumは、WebアプリケーションのテストでWebブラウザーとのやり取りを自動化するために主に使用されるツールです。ボタンのクリック、テキストの入力、Webページからのデータの抽出などのタスクを実行できるので、やり取りを自動化してWebコンテンツをスクレイピングするのに最適です。ユーザーの実際の対話操作の模倣は、Seleniumがブラウザーのコントロールに使用するWebDriverを介して可能になります。この例ではChromeを使用していますが、SeleniumはFirefox、Safari、Internet Explorerなどの他のブラウザもサポートしています。
Selenium WebDriverサービスでは、Webとのやり取りの基盤となるブラウザーの動作に影響を与えるプロキシやその他の構成を、実際のブラウザーとまったく同様に設定できます。プログラムからは、selelium.Capabilities{}
定義を使用して設定できます。
Seleniumでローカルプロキシを使用するには、selenium.go
ファイルをエディタで開き、ScrapeWithSelenium()
内のSelelium.Capabilities{}
定義を次のスニペットに置き換えます。
...nn // Define proxy settingsn proxy := selenium.Proxy{n Type: selenium.Manual,n HTTP: u0022127.0.0.1:3128u0022, // Replace with your proxy settingsn SSL: u0022127.0.0.1:3128u0022, // Replace with your proxy settingsn }nn // Configuring the WebDriver instance with the proxyn caps := selenium.Capabilities{n u0022browserNameu0022: u0022chromeu0022,n u0022proxyu0022: proxy,n }n n...n
このスニペットは、Seleniumのさまざまなプロキシパラメーターを定義しており、これがWebDriver用のSeleniumの機能の設定に使用されます。 次回の実行では、このプロキシ接続が使用されます。
次に、プロジェクトディレクトリから次のコマンドを使用して実装を実行します。
go run ./selenium.gon
出力は次のようになります。
$ go run ./selenium.gonnArticle 0: {u0022categoryu0022:u0022Newsletter âï¸u0022,u0022excerptu0022:u0022Unwind your new year celebration with new open-source projects, and keep an eye on interesting distro updates.u0022,u0022titleu0022:u0022FOSS Weekly #24.02: Mixing AI With Linux, Vanilla OS 2, and Moreu0022}nArticle 1: {u0022categoryu0022:u0022Tutorialu0022,u0022excerptu0022:u0022Wondering how to use tiling windows on GNOME? Try the tiling assistant. Here's how it works.u0022,u0022titleu0022:u0022How to Use Tiling Assistant on GNOME Desktop?u0022}nArticle 2: {u0022categoryu0022:u0022Linux Commandsu0022,u0022excerptu0022:u0022The free command in Linux helps you gain insights on system memory usage (RAM), and more. Here's how to make good use of it.u0022,u0022titleu0022:u0022Free Command Examplesu0022}nArticle 3: {u0022categoryu0022:u0022Gaming ð®u0022,u0022excerptu0022:u0022Here are the best tips to make your Linux gaming experience enjoyable.u0022,u0022titleu0022:u00227 Tips and Tools to Improve Your Gaming Experience on Linuxu0022}nArticle 4: {u0022categoryu0022:u0022Newsletter âï¸u0022,u0022excerptu0022:u0022The first edition of FOSS Weekly in the year 2024 is here. See, what's new in the new year.u0022,u0022titleu0022:u0022FOSS Weekly #24.01: Linux in 2024, GDM Customization, Distros You Missed Last Yearu0022}nArticle 5: {u0022categoryu0022:u0022Tutorialu0022,u0022excerptu0022:u0022Wondering which init service your Linux system uses? Here's how to find it out.u0022,u0022titleu0022:u0022How to Check if Your Linux System Uses systemdu0022}nArticle 6: {u0022categoryu0022:u0022Ubuntuu0022,u0022excerptu0022:u0022Learn the logic behind each step you have to follow for adding an external repository in Ubuntu and installing packages from it.u0022,u0022titleu0022:u0022Installing Packages From External Repositories in Ubuntu [Explained]u0022}nArticle 7: {u0022categoryu0022:u0022Troubleshoot ð¬u0022,u0022excerptu0022:u0022Getting a warning that the boot partition has no space left? Here are some ways you can free up space on the boot partition in Ubuntu Linux.u0022,u0022titleu0022:u0022How to Free Up Space in /boot Partition on Ubuntu Linux?u0022}nArticle 8: {u0022categoryu0022:u0022Ubuntuu0022,u0022excerptu0022:u0022Wondering which Ubuntu version you're using? Here's how to check your Ubuntu version, desktop environment and other relevant system information.u0022,u0022titleu0022:u0022How to Check Ubuntu Version Details and Other System Informationu0022}nnCheck Proxy IP {u0022ipu0022:u0022197.251.144.148u0022,u0022countryu0022:u0022GHu0022,u0022asnu0022:{u0022asnumu0022:29614,u0022org_nameu0022:u0022VODAFONE GHANA AS INTERNATIONAL TRANSITu0022},u0022geou0022:{u0022cityu0022:u0022Accrau0022,u0022regionu0022:u0022AAu0022,u0022region_nameu0022:u0022Greater Accra Regionu0022,u0022postal_codeu0022:u0022u0022,u0022latitudeu0022:5.5486,u0022longitudeu0022:-0.2012,u0022tzu0022:u0022Africa/Accrau0022,u0022lum_cityu0022:u0022accrau0022,u0022lum_regionu0022:u0022aau0022}}nn
プロキシサーバーは自分でメンテナンスできるとはいえ、多くの地域向けの新しいサーバーのセットアップ、その他のメンテナンス作業、セキュリティの問題など、さまざまな要因による制限があります。
Bright Dataプロキシサーバー
プロキシサーバーとサービスの包括的なセットを備えた、受賞歴のあるBright Dataグローバルプロキシネットワークインフラストラクチャを、さまざまなWebデータ収集用途にぜひご利用ください。
Bright Dataプロキシサーバーの広範なグローバルネットワークを利用すれば、国境を越えたさまざまな場所から簡単にアクセスしてデータを収集できます。Bright Dataは、3億5,000万を超える他に類を見ない住宅用、ISP用、データセンター用、モバイル用プロキシをはじめとして、多様なタイプのプロキシを提供しています。これらにはそれぞれ、合法性、速度、信頼性などの固有の利点があり、Webデータ収集タスクの特性に合わせてお選びいただけます。
加えて、Bright Dataプロキシローテーションシステムは高い匿名性を保証し、検出される可能性を最小限にできるため、継続的かつ大規模なWebデータ収集に最適です。
Bright Dataの住宅用プロキシを設定する
Bright Dataの住宅用プロキシは簡単に取得できます。無料トライアルにサインアップしてぜひお試しください。サインアップすると、次のような画面になります。

住宅用プロキシの開始ボタンをクリックしてください。
以下のフォームに入力するよう求められます。

このインスタンスの名前を指定します。ここでは、my_go_demo_proxy
にしましょう。プロビジョニングするIPタイプを指定する必要があります。共有を選択してください (共有プロキシを使用する場合)。次に、Webコンテンツのアクセス時に位置情報を変更するレベルを指定します。デフォルトでは、これは国レベルまたはゾーンです。リクエストしたWebページをキャッシュするかどうかを指定する必要もあります。今は、キャッシュを無効にしましょう。
この情報を入力したら、追加をクリックします。住宅用プロキシの作成とプロビジョニングが行われます。
次に、住宅用プロキシを有効にする必要があります。新規ユーザーの場合は、まず請求先情報の入力を求められます。この手順が完了したらダッシュボードに移動し、作成した住宅用プロキシをクリックします。

アクセスパラメータータブが選択されていることを確認します。
ここに、ホスト、ポート、認証情報など、住宅用プロキシの利用に必要なさまざまなパラメーターが表示されます。この情報はすぐに必要になります。
ここからいよいよ、スクレイパーの3つの実装にBright Data住宅用プロキシを統合していきます。ローカルサーバーの場合と作業が似ていますが、認証が含まれる点が異なります。また、プログラムでWebとやり取りするので、グラフィカルユーザーインターフェイスを備えたブラウザーでの操作とは異なり、プロキシサーバーからのSSL証明書を確認して受け入れることができない可能性があります。そのため、Webクライアント側のプログラムでSSL証明書の検証を無効にして、リクエストが中断されないようにする必要があります。
まず、プロジェクトディレクトリにbrightdata
というディレクトリを作成し、3つの.go
ファイルをbrightdata
ディレクトリにコピーします。次のようなディレクトリ構造になります。
.nâââ brightdatanâ âââ colly.gonâ âââ goquery.gonâ âââ selenium.gonâââ chromedrivernâââ colly.gonâââ go.modnâââ goquery.gonâââ go.sumnâââ LICENSEnâââ README.mdnâââ selenium.gonn2 directories, 11 filesnn
これから変更するのは、brightdata
ディレクトリ内のファイルです。
goqueryでBright Data住宅用プロキシを使う
ScrapeWithGoQuery()
関数内でProxyStr
変数を変更し、認証資格情報をプロキシのURLに含める必要があります。形式は、http://USERNAME:PASSWORD@HOST:PORT
です。現在の定義を次のスニペットに置き換えてください。
...nnfunc ScrapeWithGoquery() {n // Define the proxy server with username and passwordn proxyUsername := u0022usernameu0022 //Your residential proxy username n proxyPassword := u0022your_passwordu0022 //Your Residential Proxy password heren proxyHost := u0022server_hostu0022 //Your Residential Proxy Hostn proxyPort := u0022server_portu0022 //Your Port heren n proxyStr := fmt.Sprintf(u0022http://%s:%s@%s:%su0022, url.QueryEscape(proxyUsername), url.QueryEscape(proxyPassword), proxyHost, proxyPort)n n // Parse the proxy URLn...n
次に、HTTPクライアントのトランスポートを変更して、プロキシサーバーのSSL/TLS証明書の検証を無視する設定にする必要があります。まず、crypto/tls
パッケージをインポートに追加します。次に、プロキシのURLを解析し、http.Transport
定義を次のスニペットに置き換えます。
...nnfunc ScrapeWithGoquery() {n n // Parse the proxy URLn...nn //Create an http.Transport that uses the proxyn transport := u0026http.Transport{n Proxy: http.ProxyURL(proxyURL),n TLSClientConfig: u0026tls.Config{n InsecureSkipVerify: true, // Disable SSL certificate verificationn },n }nn // Create an HTTP client with the transportn... n
このスニペットは、ローカルプロキシサーバーを使用するように設定されたトランスポートでHTTPクライアントを変更します。IPアドレスは必ずプロキシサーバーのIPアドレスに置き換えてください。
次に、プロジェクトディレクトリから次のコマンドを使用してこの実装を実行します。
go run brightdata/goquery.go n
出力は次のようになります。
$ go run brightdata/goquery.go nnArticle 0: {u0022categoryu0022:u0022Newsletter âï¸u0022,u0022excerptu0022:u0022Open source rival to Twitter, a hyped new terminal and a cool new Brave/Chrome feature among many other things.u0022,u0022titleu0022:u0022FOSS Weekly #24.07: Fedora Atomic Distro, Android FOSS Apps, Mozilla Monitor Plus and Moreu0022}nArticle 1: {u0022categoryu0022:u0022Explainu0022,u0022excerptu0022:u0022Intel makes things confusing, I guess. Let's try making the processor naming changes simpler.u0022,u0022titleu0022:u0022Intel Processor Naming Changes: All You Need to Knowu0022}nArticle 2: {u0022categoryu0022:u0022Linux Commandsu0022,u0022excerptu0022:u0022The Cut command lets you extract a part of the file to print without affecting the original file. Learn more here.u0022,u0022titleu0022:u0022Cut Command Examplesu0022}nArticle 3: {u0022categoryu0022:u0022Raspberry Piu0022,u0022excerptu0022:u0022A UART attached to your Raspberry Pi can help you troubleshoot issues with your Raspberry Pi. Here's what you need to know.u0022,u0022titleu0022:u0022Using a USB Serial Adapter (UART) to Help Debug Your Raspberry Piu0022}nArticle 4: {u0022categoryu0022:u0022Newsletter âï¸u0022,u0022excerptu0022:u0022Damn Small Linux resumes development after 16 years.u0022,u0022titleu0022:u0022FOSS Weekly #24.06: Ollama AI, Zorin OS Upgrade, Damn Small Linux, Sudo on Windows and Moreu0022}nArticle 5: {u0022categoryu0022:u0022Tutorialu0022,u0022excerptu0022:u0022Zorin OS now provides a way to upgrade to a newer major version. Here's how to do that.u0022,u0022titleu0022:u0022How to upgrade to Zorin OS 17u0022}nArticle 6: {u0022categoryu0022:u0022Ubuntuu0022,u0022excerptu0022:u0022Learn the logic behind each step you have to follow for adding an external repository in Ubuntu and installing packages from it.u0022,u0022titleu0022:u0022Installing Packages From External Repositories in Ubuntu [Explained]u0022}nArticle 7: {u0022categoryu0022:u0022Troubleshoot ð¬u0022,u0022excerptu0022:u0022Getting a warning that the boot partition has no space left? Here are some ways you can free up space on the boot partition in Ubuntu Linux.u0022,u0022titleu0022:u0022How to Free Up Space in /boot Partition on Ubuntu Linux?u0022}nArticle 8: {u0022categoryu0022:u0022Ubuntuu0022,u0022excerptu0022:u0022Wondering which Ubuntu version youâre using? Hereâs how to check your Ubuntu version, desktop environment and other relevant system information.u0022,u0022titleu0022:u0022How to Check Ubuntu Version Details and Other System Informationu0022}nnCheck Proxy IP map[asn:map[asnum:7922 org_name:COMCAST-7922] country:US geo:map[city:Crown Point latitude:41.4253 longitude:-87.3565 lum_city:crownpoint lum_region:in postal_code:46307 region:IN region_name:Indiana tz:America/Chicago] ip:73.36.77.244]n
同じ記事をスクレイピングしているのに、異なる結果がプロキシIPチェックから返されたことがわかるでしょう。別の場所または国からアクセスされたからです。
CollyでBright Data住宅用プロキシを使う
CollyにはSSL/TLS検証をプログラムで無効にするメソッドがありませんが、ユーザー固有のトランスポート
を提供して、それがHTTPクライアントで使用されるようにする方法はあります。
colly.go
ファイルをエディタかIDEで開き、ScrapeWithColly()
関数内で新しいコレクタを初期化した後に、次のコードを貼り付けてください (net/url
とnet/http
のインポートを追加することを忘れないでください)。
...nfunc ScrapeWithColly() {n ...n n //Create an http.Transport that uses the proxyn transport := u0026http.Transport{n TLSClientConfig: u0026tls.Config{n InsecureSkipVerify: true, // Disable SSL certificate verificationn },n }n n // Set the collector instance to use the configured transportn c.WithTransport(transport)n n n...n
このスニペットでは、SSL検証を無効化したHTTPトランスポートを定義し、Colly withTransport()
メソッドを使用して、ネットワークリクエストを行うコレクタのトランスポートを設定しています。
ProxyStr
変数を変更し、住宅用プロキシの認証情報を格納します (goqueryで行ったのと同様)。ProxyStr
行を次のスニペットに置き換えてください。
...nn // Define the proxy server with username and passwordn proxyUsername := u0022usernameu0022 //Your residential proxy username n proxyPassword := u0022your_passwordu0022 //Your Residential Proxy password heren proxyHost := u0022server_hostu0022 //Your Residential Proxy Hostn proxyPort := u0022server_portu0022 //Your Port herenn proxyStr := fmt.Sprintf(u0022http://%s:%s@%s:%su0022, url.QueryEscape(proxyUsername), url.QueryEscape(proxyPassword), proxyHost, proxyPort)nn...n
文字列値を、住宅用プロキシのアクセスパラメーターページにある値に置き換えることを忘れないでください。
次に、プロジェクトディレクトリから次のコマンドを使用してこの実装を実行します。
go run brightdata/colly.gon
go run brightdata/colly.go nâ¦nnCheck Proxy IP map[asn:map[asnum:2856 org_name:British Telecommunications PLC] country:GB geo:map[city:Turriff latitude:57.5324 longitude:-2.3883 lum_city:turriff lum_region:sct postal_code:AB53 region:SCT region_name:Scotland tz:Europe/London] ip:86.180.236.254]nn
出力の「Check Proxy IP」を見ると、同じ認証情報が使用されているのに国が違うことがわかるでしょう。
SeleniumでBright Data住宅用プロキシを使う
Seleniumで使用する場合は、認証情報を含むプロキシURL文字列を使用するようにSelenium.Proxy{}
定義を変更する必要があります。現在のプロキシ定義を次の内容に置き換えてください。
...nn // Define the proxy server with username and passwordn proxyUsername := u0022usernameu0022 //Your residential proxy usernamen proxyPassword := u0022your_passwordu0022 //Your Residential Proxy password heren proxyHost := u0022server_hostu0022 //Your Residential Proxy Hostn proxyPort := u0022server_portu0022 //Your Port herenn proxyStr := fmt.Sprintf(u0022http://%s:%s@%s:%su0022, url.QueryEscape(proxyUsername), url.QueryEscape(proxyPassword), proxyHost, proxyPort)nn // Define proxy settingsn proxy := selenium.Proxy{n Type: selenium.Manual,n HTTP: proxyStr,n SSL: proxyStr,n }n n...n
net/url
パッケージのインポートを忘れないでください。
さまざまなプロキシパラメーターが定義されたこのスニペットがマージされて、プロキシ設定で使用されるプロキシURLが作成されます。
住宅用プロキシはこれまでに説明した実装と同様に設定されましたが、ここでは、SSL検証を無効にするオプションをChrome WebDriverに設定する必要があります。そのためにChromeCaps
定義の引数を変更して、次のように--ignore-certificate-errors
オプションを追加します。
... n caps.AddChrome(chrome.Capabilities{Args: []string{n u0022u002du002dheadless=newu0022, // Start browser without UI as a background processn u0022u002du002dignore-certificate-errorsu0022, // // Disable SSL certificate verificationn }})n...n
Seleniumは、デフォルトでは認証されたプロキシ構成をサポートしませんが、認証されたプロキシ接続用のChrome拡張機能をビルドする小さなパッケージを使用して、この問題を回避できます。
まず、このgo get
コマンドを使用して、そのパッケージをプロジェクトに追加します。
go get https://github.com/rexfordnyrk/proxyauthnn
次に、パッケージをbrightdata/selenium.go
ファイルにインポートします。ファイル先頭のインポートブロックにgithub.com/rexfordnyrk/proxyauth
行を追加してください。
次に、proxyauthパッケージのBuildExtension()
メソッドでChrome拡張機能をビルドして、Bright Data住宅用プロキシの認証情報と一緒に渡す必要があります。そのために、chromeCaps
定義の後、caps.AddChrome(chromeCaps)
行の前に、次のコードスニペットを貼り付けてください。
â¦n //Building proxy auth extension using BrightData Proxy credentialsn extension, err := proxyauth.BuildExtention(proxyHost, proxyPort, proxyUsername, proxyPassword)n if err != nil {n log.Fatal(u0022BuildProxyExtension Error:u0022, err)n }nn //including the extension to allow proxy authentication in chromen if err := chromeCaps.AddExtension(extension); err != nil {n log.Fatal(u0022Error adding Extension:u0022, err)n }nnâ¦n
このスニペットでChrome拡張機能が作成され、Chrome WebDriverに追加されます。これにより、提供されたプロキシ認証情報を介して、認証されたWebリクエストが有効になります。
プロジェクトディレクトリから次のコマンドを使用してこの実装を実行します。
go run brightdata/selenium.gon
出力は次のようになります。
$ go run brightdata/selenium.go nnArticle 0: {u0022categoryTextu0022:u0022Newsletter âï¸u0022,u0022excerptu0022:u0022Check out the promising new features in Ubuntu 24.04 LTS and a new immutable distro.u0022,u0022titleu0022:u0022FOSS Weekly #24.08: Ubuntu 24.04 Features, Arkane Linux, grep, Fedora COSMIC and Moreu0022}nâ¦nArticle 8: {u0022categoryTextu0022:u0022Ubuntuu0022,u0022excerptu0022:u0022Wondering which Ubuntu version youâre using? Hereâs how to check your Ubuntu version, desktop environment and other relevant system information.u0022,u0022titleu0022:u0022How to Check Ubuntu Version Details and Other System Informationu0022}nnCheck Proxy IP {u0022ipu0022:u0022176.45.169.166u0022,u0022countryu0022:u0022SAu0022,u0022asnu0022:{u0022asnumu0022:25019,u0022org_nameu0022:u0022Saudi Telecom Company JSCu0022},u0022geou0022:{u0022cityu0022:u0022Riyadhu0022,u0022regionu0022:u002201u0022,u0022region_nameu0022:u0022Riyadh Regionu0022,u0022postal_codeu0022:u0022u0022,u0022latitudeu0022:24.6869,u0022longitudeu0022:46.7224,u0022tzu0022:u0022Asia/Riyadhu0022,u0022lum_cityu0022:u0022riyadhu0022,u0022lum_regionu0022:u002201u0022}}nn
ここでも、出力の最後にあるIP情報を見てください。リクエストの送信に別の国が使用されていることがわかるでしょう。これは、Bright Dataプロキシローテーションシステムが動作している様子です。
ここまで見てきたとおり、Bright DataはGoアプリケーションで簡単に利用できます。最初に、Bright Dataプラットフォームで住宅用プロキシを作成し、認証情報を取得します。次に、その情報を使用して、Webでプロキシを使用するようにコードを変更します。
まとめ
Webプロキシサーバーは、インターネットでのやり取りをカスタマイズするための非常に重要なコンポーネントです。この記事では、プロキシサーバーについて、およびSquidを使用したセルフホストのプロキシサーバーをセットアップする方法について、その全体を学びました。ローカルプロキシサーバーをGoアプリケーション (今回はWebスクレイパー) に統合する方法についても説明しました。
プロキシサーバーの利用にご関心がおありでしたら、ぜひBright Dataをご検討ください。最先端のプロキシネットワークでデータを迅速・簡単に収集できます。インフラストラクチャやメンテナンス作業が増える心配はご無用です。