首页 > 解决方案 > 在 WSL 上配置 Tor + Selenium 以进行网络抓取

问题描述

如何配置 Tor 以在 WSL 上与 Selenium 一起使用?

我正在尝试将Selenium + GeckodriverTor一起使用,但我似乎无法让它们一起玩得很好。

测试 1:使用 Selenium + geckodriver 驱动 Tor。

我正在研究python3WSL。我已经将Torgeckodriver下载到我的机器上。

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

# Paths to Tor-Firefox and geckodriver executables (Windows):
firefox = '/mnt/c/Users/User/Downloads/Tor Browser/Browser/firefox.exe'
gecko = '/mnt/c/Program Files/Mozilla Firefox/geckodriver.exe'

# Create the webdriver.
binary = FirefoxBinary(firefox)
driver = webdriver.Firefox(firefox_binary=binary,executable_path=gecko) # Doesn't work.

# NOTE: a similar approach with Chrome + chromedriver + selenium works as expected. 

未创建驱动程序,python 吐出以下错误消息:

SessionNotCreatedException:消息:找不到匹配的功能集

# but, its not a problem with the geckodriver.

# Show that geckodriver works...
driver = webdriver.Firefox(executable_path=gecko)
url="https://www.google.com/"
driver.get(url)

# But, it isn't working through tor. 
driver.get('https://check.torproject.org') # Sorry, you are not using Tor.

测试 2:使用 torrequest 库随机化我的 IP 地址。

我可以用 随机化我的 IP 地址torrequest,但它不被识别为 Tor。我已经安装 torapt-get完成了 torrc 文件的一些基本配置(12)。我设置了一个 HashedControlPasstor --hash-password <password>并将其添加到我的torrc. tor我在命令行中启动了tor 。Tor 启动很吵,也许问题出在下面的警告上?

您的服务器 (IP:ADRESS:9001) 未能确认其 ORPort 可访问。在 ORPort 和 DirPort 可达之前,中继不会发布描述符。请检查您的防火墙、端口、地址、/etc/hosts 文件等。

尽管有警告,我可以用 torrequest 随机化我的 IP,但它不被识别为tor

import requests
from torrequest import TorRequest

# Add HashedControlPass.
tr=TorRequest(password='<my HashedControlPass>')

# Check initial IP.
session = requests.session()
response = session.get('http://ipecho.net/plain')
ip = response.text
print("IP address is set to: {}".format(ip)) # my actual ip

# Check new IP with tor.
response = tr.get('http://ipecho.net/plain')
ip = response.text
print("IP address is set to: {}".format(ip)) # my ip is now different.

# Check if tor is active.
response = tr.get('https://check.torproject.org')
response.text # Sorry, you are not using Tor.

测试 3:在命令行上使用 tor (WSL-Ubuntu)。

尽管以前的方法有问题,但我可以torify在命令行上成功使用。

torify wget 'https://check.torproject.org' 

产生所需的响应:

恭喜。此浏览器配置为使用 Tor。

任何想法/帮助/建议表示赞赏。

标签: python-3.xseleniumweb-scrapinggeckodrivertor

解决方案


推荐阅读