簡體   English   中英

使用 selenium 打開 Tor 瀏覽器

[英]Open tor browser with selenium

是否可以讓 selenium 使用 TOR 瀏覽器? 有沒有人可以復制粘貼的代碼?

不要使用 TBB,只需在您使用的任何瀏覽器中設置正確的代理設置。 以FF為例,像這樣:

#set some privacy settings
ff_prof.set_preference( "places.history.enabled", False )
ff_prof.set_preference( "privacy.clearOnShutdown.offlineApps", True )
ff_prof.set_preference( "privacy.clearOnShutdown.passwords", True )
ff_prof.set_preference( "privacy.clearOnShutdown.siteSettings", True )
ff_prof.set_preference( "privacy.sanitize.sanitizeOnShutdown", True )
ff_prof.set_preference( "signon.rememberSignons", False )
ff_prof.set_preference( "network.cookie.lifetimePolicy", 2 )
ff_prof.set_preference( "network.dns.disablePrefetch", True )
ff_prof.set_preference( "network.http.sendRefererHeader", 0 )

#set socks proxy
ff_prof.set_preference( "network.proxy.type", 1 )
ff_prof.set_preference( "network.proxy.socks_version", 5 )
ff_prof.set_preference( "network.proxy.socks", '127.0.0.1' )
ff_prof.set_preference( "network.proxy.socks_port", 9050 )
ff_prof.set_preference( "network.proxy.socks_remote_dns", True )

#if you're really hardcore about your security
#js can be used to reveal your true i.p.
ff_prof.set_preference( "javascript.enabled", False )

#get a huge speed increase by not downloading images
ff_prof.set_preference( "permissions.default.image", 2 )

##
# programmatically start tor (in windows environment)
##
tor_path = "C:\\this\\is\\the\\location\\of\\" #tor.exe
torrc_path = "C:\\you\\need\\to\\create\\this\\file\\torrc"

DETACHED_PROCESS = 0x00000008
#calling as a detached_process means the program will not die with your python program - you will need to manually kill it
##
# somebody please let me know if there's a way to make this a child process that automatically dies (in windows)
##
tor_process = subprocess.Popen( '"' + tor_path+'tor.exe" --nt-service "-f" "' + torrc_path + '"', creationflags=DETACHED_PROCESS )

#attach to tor controller
## imports ##
# import stem.socket
# import stem.connection
# import stem.Signal
##
tor_controller = stem.socket.ControlPort( port=9051 )

control_password = 'password'
#in your torrc, you need to store the hashed version of 'password' which you can get with: subprocess.call( '"' + tor_path+'tor.exe" --hash-password %s' %control_password )

stem.connection.authenticate( tor_controller, password=control_password )

#check that everything is good with your tor_process by checking bootstrap status
tor_controller.send( 'GETINFO status/bootstrap-phase' )
response = worker.tor_controller.recv()
response = response.content()

#I will leave handling of response status to you

是的,可以讓 selenium 使用 TOR 瀏覽器。

我能夠在 Ubuntu 和 Mac OS X 上這樣做。

有兩件事必須發生:

  1. 將二進制路徑設置為 Tor 使用的 firefox 二進制文件。 在 Mac 上,此路徑通常是/Applications/TorBrowser.app/Contents/MacOS/firefox 在我的 Ubuntu 機器上,它是/usr/bin/tor-browser/Browser/firefox

  2. Tor 瀏覽器通過 Vidalia 或 Tor 安裝使用位於 127.0.0.1:9150 的 SOCKS 主機。 從 Finder 啟動 Tor 一次並保持打開狀態,以便 Vidalia 運行。 使用 selenium 啟動的實例也將使用 Vidalia 啟動的 SOCKS 主機。

這是完成這兩件事的代碼。 我在 Mac OS X Yosemite 上運行這個:

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


# path to the firefox binary inside the Tor package
binary = '/Applications/TorBrowser.app/Contents/MacOS/firefox'
if os.path.exists(binary) is False:
    raise ValueError("The binary path to Tor firefox does not exist.")
firefox_binary = FirefoxBinary(binary)


browser = None
def get_browser(binary=None):
    global browser  
    # only one instance of a browser opens, remove global for multiple instances
    if not browser: 
        browser = webdriver.Firefox(firefox_binary=binary)
    return browser

if __name__ == "__main__":
    browser = get_browser(binary=firefox_binary)
    urls = (
        ('tor browser check', 'https://check.torproject.org/'),
        ('ip checker', 'http://icanhazip.com')
    )
    for url_name, url in urls:
        print "getting", url_name, "at", url
        browser.get(url)

在 Ubuntu 系統上,我能夠通過 selenium 運行 Tor 瀏覽器。 這台機器有在 9051 端口運行的 Tor 和在 8118 端口使用 Tor 的 privoxy http 代理。為了讓 Tor 瀏覽器通過 Tor 檢查頁面,我必須將 http 代理設置為 privoxy。

from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium import webdriver
browser = None

proxy_address = "127.0.0.1:8118"
proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    'httpProxy': proxy_address,
})

tor = '/usr/bin/tor-browser/Browser/firefox'
firefox_binary = FirefoxBinary(tor)

urls = (
    ('tor_browser_check', 'https://check.torproject.org/'),
    ('icanhazip', 'http://icanhazip.com'),
)
keys, _ = zip(*urls)
urls_map = dict(urls)

def get_browser(binary=None, proxy=None):
    global browser
    if not browser:
        browser = webdriver.Firefox(firefox_binary=binary, proxy=proxy)
    return browser

if __name__ == "__main__":
    browser = get_browser(binary=firefox_binary, proxy=proxy)
    for resource in keys:
        browser.get(urls_map.get(resource))

// 只需檢查您的 Tor 瀏覽器的端口號並在 // 代碼中相應地更改它

from selenium import webdriver
profile=webdriver.FirefoxProfile()
profile.set_preference('network.proxy.type', 1)
profile.set_preference('network.proxy.socks', '127.0.0.1')
profile.set_preference('network.proxy.socks_port', 9150)
browser=webdriver.Firefox(profile)
browser.get("http://yahoo.com")
browser.save_screenshot("screenshot.png")
browser.close()

要使用Selenium驅動的GeckoDriver打開瀏覽器,您需要:

  • 下載並安裝TOR 瀏覽器

  • 下載最新的GeckoDriver v0.26.0並將其放入您的系統中。

  • 安裝最新的Mozilla Firefox v77.0.1瀏覽器。

  • 您可以使用以下代碼塊打開啟用TOR 的瀏覽器:

     from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import FirefoxProfile import os torexe = os.popen(r'C:\\Users\\username\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Tor\\tor.exe') profile = FirefoxProfile(r'C:\\Users\\username\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Data\\Browser\\profile.default') profile.set_preference('network.proxy.type', 1) profile.set_preference('network.proxy.socks', '127.0.0.1') profile.set_preference('network.proxy.socks_port', 9050) profile.set_preference("network.proxy.socks_remote_dns", False) profile.update_preferences() firefox_options = webdriver.FirefoxOptions() firefox_options.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe' driver = webdriver.Firefox(firefox_profile= profile, options = firefox_options, executable_path=r'C:\\WebDrivers\\geckodriver.exe') driver.get("http://check.torproject.org")
  • 瀏覽器快照:

torFirefox_torproject


使用 Firefox Nightly 的替代方法

作為替代方案,您還可以下載、安裝和使用最新的Firefox Nightly v79.0a1瀏覽器。

  • 代碼塊:

     from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import FirefoxProfile import os torexe = os.popen(r'C:\\Users\\username\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Tor\\tor.exe') profile = FirefoxProfile(r'C:\\Users\\username\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Data\\Browser\\profile.default') profile.set_preference('network.proxy.type', 1) profile.set_preference('network.proxy.socks', '127.0.0.1') profile.set_preference('network.proxy.socks_port', 9050) profile.set_preference("network.proxy.socks_remote_dns", False) profile.update_preferences() firefox_options = webdriver.FirefoxOptions() firefox_options.binary_location = r'C:\\Program Files\\Firefox Nightly\\firefox.exe' driver = webdriver.Firefox(firefox_profile= profile, options = firefox_options, executable_path=r'C:\\WebDrivers\\geckodriver.exe') driver.get("http://check.torproject.org")
  • 瀏覽器快照:

torNightly_torproject


使用 Chrome 的替代方法

作為替代方案,您還可以下載、安裝和使用最新的Chrome v84瀏覽器。

  • 代碼塊:

     from selenium import webdriver import os torexe = os.popen(r'C:\\Users\\username\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Tor\\tor.exe') PROXY = "socks5://localhost:9050" # IP:PORT or HOST:PORT options = webdriver.ChromeOptions() options.add_argument('--proxy-server=%s' % PROXY) driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\\WebDrivers\\chromedriver.exe') driver.get("http://check.torproject.org")
  • 瀏覽器快照:

torChrome_torproject


參考

您可以在以下位置找到一些相關的詳細討論:

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

#path to TOR binary
binary = FirefoxBinary(r'...\Tor Browser\Browser\firefox.exe')
#path to TOR profile
profile = FirefoxProfile(r'...\Tor Browser\Browser\TorBrowser\Data\Browser\profile.default')

driver = webdriver.Firefox(firefox_profile= profile, firefox_binary= binary)
driver.get("http://icanhazip.com")
driver.save_screenshot("screenshot.png")
driver.quit()

在 Windows 10 上使用 Python 3.5.1

很多答案都朝着正確的方向發展,但這正是對我有用的:

在 Ubuntu 上:

您需要使用 apt 命令或其他方法安裝 Tor,但不需要使用二進制版本。

安裝指南:

https://linuxconfig.org/how-to-install-tor-browser-in-ubuntu-18-04-bionic-beaver-linux

在 sample.py 中,您可能需要:

  • 將 Firefox 的配置文件設置為大部分時間位於/etc/tor/ torrc
  • 將二進制文件設置為 Tor 的 Firefox 二進制文件,因為 Tor 只是在 Firefox 之上構建的一系列配置。

您還需要 geckodriver 使用 selenium 自動化 firefox:

注意以下事項:

  • “network.proxy.socks_port”= 9150
  • 內部 torrc ControlPort 9050, CookieAuthentication 1
  • 打開 TorBrowser
  • sudo lsof -i -P -n | grep LISTEN sudo lsof -i -P -n | grep LISTEN腳本中tor網絡的LISTEN端口必須相同
  • 運行 python 腳本,同時TorBrowser 打開

感謝 user2426679 https://stackoverflow.com/a/21836296/3816638的設置。

from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.firefox.options import Options
import subprocess
import os

profileTor = '/etc/tor/' #  torrc
binary = os.path.expanduser("~/.local/share/torbrowser/tbb/x86_64/tor-browser_en-US/Browser/firefox")

firefox_binary = FirefoxBinary(binary)
firefox_profile = FirefoxProfile(profileTor)


#set some privacy settings
firefox_profile.set_preference( "places.history.enabled", False )
firefox_profile.set_preference( "privacy.clearOnShutdown.offlineApps", True )
firefox_profile.set_preference( "privacy.clearOnShutdown.passwords", True )
firefox_profile.set_preference( "privacy.clearOnShutdown.siteSettings", True )   
firefox_profile.set_preference( "privacy.sanitize.sanitizeOnShutdown", True )
firefox_profile.set_preference( "signon.rememberSignons", False )
firefox_profile.set_preference( "network.cookie.lifetimePolicy", 2 )
firefox_profile.set_preference( "network.dns.disablePrefetch", True )
firefox_profile.set_preference( "network.http.sendRefererHeader", 0 )

#set socks proxy
firefox_profile.set_preference( "network.proxy.type", 1 )
firefox_profile.set_preference( "network.proxy.socks_version", 5 )
firefox_profile.set_preference( "network.proxy.socks", '127.0.0.1' )
firefox_profile.set_preference( "network.proxy.socks_port", 9150 )
firefox_profile.set_preference( "network.proxy.socks_remote_dns", True )

#if you're really hardcore about your security
#js can be used to reveal your true i.p.
firefox_profile.set_preference( "javascript.enabled", False )

#get a huge speed increase by not downloading images
firefox_profile.set_preference( "permissions.default.image", 2 )

options = Options()
options.set_headless(headless=False)

driver = webdriver.Firefox(firefox_profile=firefox_profile,firefox_options=options)

print(driver)

driver.get("https://check.torproject.org/")
driver.save_screenshot("screenshot.png")

使用紅寶石,

profile = Selenium::WebDriver::Firefox::Profile.new
profile.proxy = Selenium::WebDriver::Proxy.new :socks => '127.0.0.1:9050' #port where TOR runs
browser = Watir::Browser.new :firefox, :profile => profile

要確認您正在使用 Tor,請使用https://check.torproject.org/

我調查了這個,除非我弄錯了,否則從表面上看這是不可能的。

不能這樣做的原因是:

  • Tor 瀏覽器基於 Firefox 代碼。
  • Tor 瀏覽器對 Firefox 代碼有特定的補丁,以防止外部應用程序與 Tor 瀏覽器通信(包括阻止 Components.Interfaces 庫)。
  • Selenium Firefox WebDriver 通過 Javascript 庫與瀏覽器通信,如前所述,這些庫被 Tor 瀏覽器阻止。

這大概是因為 Tor 瀏覽器之外的人在你的盒子上或通過互聯網知道你的瀏覽。

您的選擇是:

  • 通過 Firefox 使用 Tor 代理而不是 Tor 瀏覽器(請參閱問題評論中的鏈接)。
  • 使用 Tor 瀏覽器補丁重建 Firefox 源代碼,排除那些阻止與 Tor 瀏覽器進行外部通信的補丁。

我建議前者。

作為僅控制 Firefox 的 Selenium 的更新替代品,請查看Marionette 要與 Tor 瀏覽器一起使用,請在啟動時通過以下方式啟用牽線木偶

Browser/firefox -marionette

(在捆綁包內)。 然后,您可以通過連接

from marionette import Marionette
client = Marionette('localhost', port=2828);
client.start_session()

並加載一個新頁面,例如通過

url='http://mozilla.org'
client.navigate(url);

有關更多示例,有一個 教程


較舊的答案

Tor 項目對其瀏覽器進行了selenium 測試 它的工作原理如下:

from selenium import webdriver
ffbinary = webdriver.firefox.firefox_binary.FirefoxBinary(firefox_path=os.environ['TBB_BIN'])
ffprofile = webdriver.firefox.firefox_profile.FirefoxProfile(profile_directory=os.environ['TBB_PROFILE'])
self.driver = webdriver.Firefox(firefox_binary=ffbinary, firefox_profile=ffprofile)
self.driver.implicitly_wait(30)
self.base_url = "about:tor"
self.verificationErrors = []
self.accept_next_alert = True
self.driver.get("http://check.torproject.org/")
self.assertEqual("Congratulations. This browser is configured to use Tor.", driver.find_element_by_css_selector("h1.on").text)

如您所見,這將環境變量TBB_BINTBB_PROFILE用於瀏覽器包和配置文件。 您可以在代碼中對這些進行硬編碼。

System.setProperty("webdriver.firefox.marionette", "D:\\Lib\\geckodriver.exe");
        String torPath = "C:\\Users\\HP\\Desktop\\Tor Browser\\Browser\\firefox.exe";
        String profilePath = "C:\\Users\\HP\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Data\\Browser\\profile.default";

        File torProfileDir = new File(profilePath);
        FirefoxBinary binary = new FirefoxBinary(new File(torPath));
        FirefoxProfile torProfile = new FirefoxProfile(torProfileDir);

        FirefoxOptions options = new FirefoxOptions();
        options.setBinary(binary);
        options.setProfile(torProfile);
        options.setCapability(FirefoxOptions.FIREFOX_OPTIONS,options);
        WebDriver driver = new FirefoxDriver(options);

參考答案@undetected Selenium。 如果您在 windows 中添加(或包含)PATH:r'C:\Program Files\Mozilla Firefox\firefox.exe' 和 r'C:\WebDrivers\geckodriver.exe',那么您可以使用縮短的代碼塊。 下面我展示了一段對我有用的代碼:

import os

from selenium.webdriver import Firefox
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.firefox.options import Options

# Variable with the URL of the website.
my_url = "http://check.torproject.org"

# Preparing of the Tor browser for the work.
torexe = os.popen(\
    r"C:\Users\olive\OneDrive\Pulpit\Tor Browser\Browser\firefox.exe")
profile = FirefoxProfile(\
    r"C:\Users\olive\OneDrive\Pulpit\Tor Browser\Browser\TorBrowser\Data"+\
    "\Browser\profile.default")
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.socks", "127.0.0.1")
profile.set_preference("network.proxy.socks_port", 9150)
profile.set_preference("network.proxy.socks_remote_dns", False)
profile.update_preferences()
firefox_options = Options()
driver = Firefox(firefox_profile= profile, options = firefox_options)
driver.get(my_url)

不再需要手動下載webdriver,可以這樣使用:

pip 安裝 selenium
pip 安裝 webdriver-manager

import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

# Chrome e Proxy Tor
servico = Service(ChromeDriverManager().install())
proxy = "socks5://127.0.0.1:9150"  # Tor
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(f"--proxy-server={proxy}")
navegador = webdriver.Chrome(service=servico, options=chrome_options)

check_tor = 'https://check.torproject.org/'

navegador.get(check_tor)
time.sleep(10)

*** 顯然 Tor 瀏覽器需要打開。**

https://i.stack.imgur.com/krKMO.png

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM