How to open and close Tor browser automatically with Python
<p>I am playing around with web scraping and Tor.</p>

<p>I managed to make it work with both <code>requests</code> and <code>Selenium</code> + PhantomJS. However, I need that the Tor browser is opened for the script to work.</p>

<p>This is why I am trying now to automatise the complete process; that is: open Tor browser automatically, run some script and at the end close the browser automatically. But I am struggling with it.</p>

<pre><code>#open Tor browser
os.system('open /Applications/TorBrowser.app')

#code to scrape

#close Tor browser
???
</code></pre>

<h2>Open</h2>

<p>To open the browser, some other options I found out there are not working.</p>

<pre><code>import subprocess
subprocess.Popen('/Applications/TorBrowser.app') #permission denied
</code></pre>

<p>or</p>

<pre><code>os.system('start /Applications/TorBrowser.app') #sh: start: command not found
</code></pre>

<p>However, the following line worked:</p>

<pre><code>os.system('open /Applications/TorBrowser.app')
</code></pre>

<h2>Close</h2>

<p>The main problem is to close the browser afterwards, as none of the commands found in other posts worked.</p>

<p>Those include:</p>

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

<p>or</p>

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

<p>or</p>

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

<hr>

<ul>
<li><p>Any suggestions of how to close it?</p></li>
<li><p>And is there a better way to open it?</p></li>
</ul>

<p><em>Edit</em>: I'm on Mac with Python 3.</p>