Tag Archives: proxy

Using Python urllib2 via Tor

If socks is not installed:

sudo easy_install SocksiPy-branch

Then the following code to check the new IP:

import socks
import socket
def create_connection(address, timeout=None, source_address=None):
    sock = socks.socksocket()
    sock.connect(address)
    return sock

socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)

socket.socket = socks.socksocket
socket.create_connection = create_connection

import urllib2

try:
    # Check IP
    print urllib2.urlopen("http://almien.co.uk/m/tools/net/ip/").read()
    # Change and check user-agent which is normally Python-Urllib2
    req = urllib2.Request("http://whatismyuseragent.dotdoh.com/")
    req.add_header('User-agent', 'Mozilla 5.10')
    res = urllib2.urlopen(req)
    print res.read()
except urllib2.HTTPError, e:
    print e.code
except urllib2.URLError, e:
    print e.args

Selenium with Tor+Firefox (Mac)

Install Selenium:

sudo easy_install selenium

If Homebrew is not installed:

ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)"

Install Tor:

brew install Tor

Run Tor:

tor

In another terminal window, run the python code to open Firefox+Tor and save a screenshot via Selenium:

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', 9050)
browser=webdriver.Firefox(profile)
browser.get("http://yahoo.com")
browser.save_screenshot("/Users/admin/Pictures/screenshot.png")
browser.close()

See also: