Urllib2 using Tor and socks in python

2019-09-08 08:50发布

I'm trying to crawl websites in Python using tor. I tried below code, which gives the IP used by tor, trying this code for 2-3 times gives me different IP's from different countries. I want IP's from specific country eg India. Can we do it using tor and socks?

import socks
import socket
import urllib2    
socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, "127.0.0.1", 9050)
socket.socket = socks.socksocket
print urllib2.urlopen('http://my-ip.herokuapp.com').read()

1条回答
SAY GOODBYE
2楼-- · 2019-09-08 09:49

To get ip from specific country you have to set two parameters ExitNodes={countrycode} and StrictNodes=1.Here for India country code is {in}.To know country code check http://www.b3rn3d.com/blog/2014/03/05/tor-country-codes/. Using python you can set the these parameters as follows

Code:-

import socks
import socket
import urllib2    

def newIdentity(self):
        socks.setdefaultproxy()
        s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect(("127.0.0.1", 9051))
        s.send('AUTHENTICATE "my_password" \r\n')
        response = s.recv(128)
        if response.startswith("250"):
            s.send("SETCONF ExitNodes={in}\r\n")
            s.send("SETCONF StrictNodes=1\r\n")
            s.send("SIGNAL NEWNYM\r\n")
        s.close()
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
        socket.socket = socks.socksocket
if __name__ == '__main__':
newIdentity()
print urllib2.urlopen('http://my-ip.herokuapp.com').read()
查看更多
登录 后发表回答