Urllib2 using Tor and socks in python

孤街浪徒 提交于 2020-01-25 18:00:32

问题


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:


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()


来源:https://stackoverflow.com/questions/27957470/urllib2-using-tor-and-socks-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!