如何使用Python自动打开和关闭Tor浏览器

时间:2016-10-20 18:29:54

标签: python python-3.x tor

我正在玩网络抓取和Tor。

我设法让它与os.system('start /Applications/TorBrowser.app') #sh: start: command not found os.system('open /Applications/TorBrowser.app') + PhantomJS一起使用。但是,我需要打开Tor浏览器才能使脚本正常工作。

这就是我现在尝试自动完成整个过程的原因;即:自动打开Tor浏览器,运行一些脚本,最后自动关闭浏览器。但我正在努力解决它。

os.system("taskkill /im /Applications/TorBrowser.app /f") #sh: taskkill: command not found

打开

要打开浏览器,我发现的其他一些选项无效。

os.system("kill /Applications/TorBrowser.app") #sh: line 0: kill: /Applications/TorBrowser.app: arguments must be process or job IDs

os.close('/Applications/TorBrowser.app') #TypeError: an integer is required (got type str)

但是,以下一行有效:

for i in d:

关闭

主要问题是之后关闭浏览器,因为其他帖子中找不到任何命令。

包括:

{{1}}

{{1}}

{{1}}
  • 有关如何关闭它的任何建议吗?

  • 还有更好的方式来打开它吗?

编辑:我使用Python 3在Mac上。

1 个答案:

答案 0 :(得分:3)

This worked for me:

from selenium import webdriver
import os
import subprocess
#start Tor
sproc=subprocess.Popen('"C:\\Users\\My name\\Desktop\\Tor Browser\\Browser\\firefox.exe"' )

#start PhantomJS
service_args = [ '--proxy=localhost:9150', '--proxy-type=socks5', ]
driver = webdriver.PhantomJS(service_args=service_args)
#get page
driver.get("https://stackoverflow.com/questions/40161921/how-to-open-and-close-tor-browser-automatically-with-python")
print(driver.page_source)
driver.close()
#kill process
sproc.kill()

I think you should add some time pauses between commands:

import time
time.sleep(20)# wait 20 seconds 

Another way to open Tor:

os.system('"C:\\Users\\My Name\\Desktop\\Tor Browser\\Browser\\firefox.exe"' )

But this time your command will wait until the called process stops himself (may be user will close it). According to your question it is not what you want. To control executing process let it runs and use special variable to kill it whenever you want.

Also pay attention to string path: double quotes inside single quotes. There are other ways to pass strings with spaces to system commands, for example: running an outside program (executable) in python?.