LoginSignup
5
4

More than 3 years have passed since last update.

【Pyhon】Torを使用してスクレイピングする

Last updated at Posted at 2020-08-10

今回はTorを使用したスクレイピングについてのメモです。Torを使用して何かやらかしても、この記事と個人の一切の責任をおいません。

Torとは

盗聴防止やプライバシー保護を目的に開発されたブラウザです。オニオンルーティングと呼ばれる技術で、接続ルートをほぼ匿名化できます。ダークウェブに接続する際のブラウザとして有名です。

TorをHomebrewでインストール

$ brew install tor

サーバーを動かす

$ brew services start tor

Torを使用してWebページに複数のGETリクエストを送信

Torを使用して、スクレイピングのリクエストを送信するコードを紹介します。

Requests版

ソフトウェアパッケージRequestsをインストール
https://requests-docs-ja.readthedocs.io/en/latest/user/install/

$ pip install requests

ソース

tor.py
import requests

def get_tor_session():
    session = requests.session()
    session.proxies = {'http':  'socks5://127.0.0.1:9050',
                       'https': 'socks5://127.0.0.1:9050'}
    # こっちでもいい
    # session.proxies = {"http": "socks5://localhost:9050", "https": "socks5://localhost:9050"}
    return session

# Torを使用した場合
print('Torした')
session = get_tor_session()
print(session.get("http://httpbin.org/ip").text)

# Torを使用していない場合
print('Torしてない')
print(requests.get("http://httpbin.org/ip").text)

ターミナルで実行

$ python tor.py

出力結果

$ py proxy.py
Torした
{
  "origin": "185.220.101.209"
}

Torしてない
{
  "origin": "126.224.155.158"
}

関連記事
PyhonのスクレイピングでTorを使用してChromeにアクセスする

参考
https://www.thepythoncode.com/code/using-proxies-using-requests-in-python
https://2019.www.torproject.org/docs/faq.html.en#torrc
https://www.it-swarm.dev/ja/python/tor%E3%81%A7python%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%A6%E3%83%AA%E3%82%AF%E3%82%A8%E3%82%B9%E3%83%88%E3%82%92%E8%A1%8C%E3%81%86/1053483225/
https://www.366service.com/jp/qa/81b67eb666ad284089fd2ea7e04d6f3d
https://qiita.com/koharite/items/731fcf5146c7b0c4e800

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4