2013-02-03 86 views
1

我想从选择列表中选择一个随机的URL,但它不工作。这里是我的代码:Python的随机URL选择

import urllib, urllib2, sys 
num = sys.argv[1] 
print 'Started' 
phones = [ 
'http://1.1.1.6/index.htm,' 
'http://1.1.1.5/index.htm,' 
'http://1.1.1.4/index.htm,' 
'http://1.1.1.3/index.htm,' 
'http://1.1.1.2/index.htm,' 
'http://1.1.1.1/index.htm' 
] 
from random import choice 
data = urllib.urlencode({"NUMBER":num, "DIAL":"Dial", "active_line":1}) 
while 1: 
    for phone in phones: 

         urllib2.urlopen(choice(phone),data) # make call 
         urllib2.urlopen(choice(phone)+"?dialeddel=0") # clear 
logs 

这是错误我得到

File "p.py", line 21, in ? 
    urllib2.urlopen(choice(phone),data) # make call 
    File "/usr/lib64/python2.4/urllib2.py", line 130, in urlopen 
    return _opener.open(url, data) 
    File "/usr/lib64/python2.4/urllib2.py", line 350, in open 
    protocol = req.get_type() 
    File "/usr/lib64/python2.4/urllib2.py", line 233, in get_type 
    raise ValueError, "unknown url type: %s" % self.__original 
ValueError: unknown url type: 5 

任何帮助表示赞赏。谢谢!

+0

选择(“你好”) - >一个字母...选项(电话)将只返回URL –

回答

4

您的逗号位于您的字符串内部。因此,您的手机变量是单个大字符串的列表。你的随机选择是给你一个字符串中的单个字符。它改成这样:

phones = [ 
    'http://1.1.1.6/index.htm', 
    'http://1.1.1.5/index.htm', 
    'http://1.1.1.4/index.htm', 
    'http://1.1.1.3/index.htm', 
    'http://1.1.1.2/index.htm', 
    'http://1.1.1.1/index.htm', 
] 

而且你不应该遍历的手机,但简单地使用random.choice(phones)选择电话。

此外,你正在为你的两个URL调用选择一个不同的随机电话,我猜这不是你想要的。这是一个完整的,重构的代码。

import urllib, urllib2, sys, random 

phones = [ 
    'http://1.1.1.6/index.htm', 
    'http://1.1.1.5/index.htm', 
    'http://1.1.1.4/index.htm', 
    'http://1.1.1.3/index.htm', 
    'http://1.1.1.2/index.htm', 
    'http://1.1.1.1/index.htm', 
] 

num = sys.argv[1] 
data = urllib.urlencode({"NUMBER": num, "DIAL": "Dial", "active_line": 1}) 
while 1: 
    phone = random.choice(phones) 
    urllib2.urlopen(phone, data) # make call 
    urllib2.urlopen(phone + "?dialeddel=0") # clear logs 
+0

的一个字母我都用过这个,它第一次成功地使用随机,但在那之后,电话不再打电话。使用旧的代码,它会继续呼叫,直到我停止它,但只有列表中的第一个电话。 – user1947236

0

你可以尝试得到一个随机指数

import random 
phones = [ 
'http://1.1.1.6/index.htm', 
'http://1.1.1.5/index.htm', 
'http://1.1.1.4/index.htm', 
'http://1.1.1.3/index.htm', 
'http://1.1.1.2/index.htm', 
'http://1.1.1.1/index.htm', 
] 

index random.randrange(0, len(phones)-1) 
phones[index]