Torで接続元を匿名化しスクレイピング [Python]
環境
- Ubuntu 16.04
- Python 3.8.2
現在のIPアドレスを確認
torを導入する前に、現在のIPアドレスを確認してみる。
現在のIPアドレスの取得については、過去記事でまとめたので、参考にされたし。
インストール
Torのインストール
$ sudo apt install tor
PySocketsのインストール
$ pip install PySocks
以上で、インストール作業は完了
PythonでTorを介したスクレイピング
import urllib.request, urllib.error
from bs4 import BeautifulSoup
import socks, socket
socks.set_default_proxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050)
socket.socket = socks.socksocket
def fetch_html(url):
res = urllib.request.urlopen(url)
return BeautifulSoup(res, 'html.parser')
# 現在のグローバルIPアドレスを返す
html = fetch_html('http://checkip.dyndns.com/')
current_ip = html.body.text.split(': ')[1]
# Torを使っているかを返す
html = fetch_html('https://check.torproject.org/')
is_tor = html.find('h1')['class'][0] != 'off'
print('You are using tor.' if is_tor else 'You are not using tor.')
print('Current IP address is ' + current_ip)
上記のスクリプトを実行すると、Torを介したIPアドレスが表示されることを確認できる。つまり、自分のグローバルIPを隠した状態で、requestができるということになる。
6行目まででtorを介した通信ができるようになっている。
ちなみに、Torはプロキシとしてsocks5://localhost:9050を使用しているためPySocketsを用いており、ポートは9050に設定。






ディスカッション
コメント一覧
まだ、コメントがありません