Below are two functions that work no problem in my current script. They are written to be ran in Python 2.7.x
def tor_browser_initialise():
""" This function checks whether the Tor Browser is running. If it isn't,
it will open the Tor Browser.
"""
processlist = []
for p in psutil.process_iter():
try:
process = psutil.Process(p.pid)
pname = process.name()
processlist.append(pname)
except:
continue
if "tor.exe" not in processlist:
process = subprocess.Popen(r"C:\Program Files (x86)\Tor Browser\Browser\firefox.exe", stdout=subprocess.PIPE)
time.sleep(30)
def connect_tor(url):
""" This function accepts a URl as an argument. It accesses the URL via TOR before
returning the HTML source code to the function that called it. This function also
uses random browser information.
"""
LOCALHOST = "127.0.0.1"
PORT = 9150
useragent_list = ['Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/29.0',
'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1944.0 Safari/537.36',
'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0',
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',
'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14',
'Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30']
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, LOCALHOST, PORT)
socket.socket = socks.socksocket
request = urllib2.Request(url)
request.add_header('User-Agent', random.choice(useragent_list))
response = urllib2.urlopen(request)
return response
I'd like to know if there is a more concise and Pythonic way of writing the two functions. I haven't listed the dependant libraries / modules at the beginning of the code, but it does work correctly.