小编典典

Selenium WebDriver + Tor作为Stem的代理?

selenium

我需要确认是否可以将Stem用于启动暴露127.0.0.1:port的Tor进程,然后在selenium脚本上将其用作代理(SOCKS)。

我在Windows上使用Python 3.4.2,Stem 1.3.0和Tor(tor-win32-tor-0.2.5.10专家包)。

这段代码可与标准SOCKS代理一起使用。

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

profile = 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', 9000)

driver = webdriver.Firefox(profile)
driver.implicitly_wait(30)
driver.get('http://www.reddit.com')

但是我无法使其与Tor作为代理一起工作。我试图创建一个Tor过程,并创建了它。但是我真的不知道它是否工作正常。我没有错误tor_error_log.txt

# File: stem_process.py
import stem.process
import stem

stem.process.launch_tor_with_config(
  config = {
    'SocksPort': '9000',
    'ControlPort': '9051',
    'ExitNodes': '{us}',
    'Log': [
      'NOTICE stdout',
      'ERR file c:\\tor-win32-tor-0.2.5.10\\Tor\\tor_error_log.txt',
    ],
  },
  tor_cmd = 'C:\\tor-win32-tor-0.2.5.10\\Tor\\tor.exe',
)

然后,我尝试了两种方法来创建连接或进行身份验证。第一个是使用withstem.control.controller。而第二个在较低的水平stem.socketstem.connection

第一个:

# File: stem_test1.py
from stem.control import Controller

with Controller.from_port(address='127.0.0.1', port=9051) as controller: #port = 9051
  controller.authenticate()

  print("Tor is running version %s" % controller.get_version())

'''
# Output:
Tor is running version 0.2.5.10 (git-13318a95ddfbbf8d)
'''

第二个:

# File: stem_test2.py
import sys
import stem
import stem.connection
import stem.socket

if __name__ == '__main__':
  try:
    control_socket = stem.socket.ControlPort(port = 9051)
    stem.connection.authenticate(control_socket)
  except stem.SocketError as exc:
    print('Unable to connect to tor on port 9051: %s' % exc)
    sys.exit(1)
  except stem.connection.AuthenticationFailure as exc:
    print('Unable to authenticate: %s' % exc)
    sys.exit(1)

  print("Issuing 'GETINFO version' query...\n")
  control_socket.send('GETINFO version')
  print(control_socket.recv())

'''
# Output:
Issuing 'GETINFO version' query...

version=0.2.5.10 (git-13318a95ddfbbf8d)
OK
'''

而如果没有错误都跑......但是当我使用的代码来调用与火狐的webdriver实例127.0.0.1:9000作为代理(也试过用127.0.0.1:9051,因为我真的不知道之间的区别socksPortcontrolPort)这是行不通的。


阅读 375

收藏
2020-06-26

共1个答案

小编典典

Stem无法创建一个Tor过程,它只能创建一个库,用于通过控制端口连接到现有的Tor服务器以进行检查/控制。

要创建Tor进程本身,您需要让系统使用upstart / launchctl /
etc启动它。另外,您也可以tor从命令行输入(如果已安装),它将在前台运行。

这样,要使用词干,您需要将torrc编辑为a。启用ControlPort,以及b。设置身份验证方法(cookieauth或存储在torc中的哈希密码)。默认的SocksPort为9050,ControlPort为9051。

SocksPort是您路由流量(即Firefox)通过的端口,ControlPort是您连接到的端口。请注意,仅在您甚至需要茎时,因为似乎您正在尝试使用它启动tor实例(那是不可行的),如果您使其在系统香草上运行,它将与设置好硒/火狐(好吧,默认端口是9050而不是9000)

2020-06-26