Urllib2在python中使用Tor和socks [英] Urllib2 using Tor and socks in python
问题描述
我正在尝试使用tor抓取Python中的网站。我尝试下面的代码,它给出了tor使用的IP,尝试这个代码2-3次给了我不同国家的不同IP。我想要来自特定国家的印度的IP。我们可以使用tor和袜子吗?
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()
推荐答案
从特定国家/地区获取IP您必须设置两个参数 ExitNodes = {countrycode} 和 StrictNodes = 1 。印度国家/地区代码为 {in} 。了解国家/地区代码检查 http://www.b3rn3d.com/blog/ 2014/03/05 / TOR-国家代码/ 。
使用python你可以设置这些参数如下
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
代码: -
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()
这篇关于Urllib2在python中使用Tor和socks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!