我需要从 ip 列表中提取所有 url, 我写了这个 python 脚本,但我在多次提取相同的 ip 时遇到问题(更多线程是使用相同的 ip 创建的)。 谁能使用多线程改进我的解决方案?
对不起我的英语 谢谢大家
import urllib2, os, re, sys, os, time, httplib, thread, argparse, random
try:
ListaIP = open(sys.argv[1], "r").readlines()
except(IOError):
print "Error: Check your IP list path\n"
sys.exit(1)
def getIP():
if len(ListaIP) != 0:
value = random.sample(ListaIP, 1)
ListaIP.remove(value[0])
return value
else:
print "\nListaIPs sa terminat\n"
sys.exit(1)
def extractURL(ip):
print ip + '\n'
page = urllib2.urlopen('http://sameip.org/ip/' + ip)
html = page.read()
links = re.findall(r'href=[\'"]?([^\'" >]+)', html)
outfile = open('2.log', 'a')
outfile.write("\n".join(links))
outfile.close()
def start():
while True:
if len(ListaIP) != 0:
test = getIP()
IP = ''.join(test).replace('\n', '')
extractURL(IP)
else:
break
for x in range(0, 10):
thread.start_new_thread( start, () )
while 1:
pass
最佳答案
使用threading.Lock
。锁应该是全局的,并且在您创建 IP 列表时创建。
lock.acquire
在 getIP()
并在您离开该方法之前释放
它。
您看到的是,线程 1 执行 value=random.sample
,然后线程 2 也在 之前执行 value=random.sample
> 线程 1 到达 remove
。所以当线程 2 到达那里时,该项目仍在列表中。
因此,两个线程都有机会获得相同的 IP。
关于Python 多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13917311/