我怎样才能得到随机文本&循环浏览文本文件,直到它随机获取所有文本1 {1}

时间:2017-08-25 14:44:49

标签: python python-3.x

编辑&添加以下代码: 我的主要问题是我在文件1和文件中有代理。用户代理文件2&我正在同时更改它们,但现在我想随机选择更改它们和它们。将它们发送到profile.set_preference(),但它只是随机选择1个代理,然后每次都使用相同的代理。请有人帮助我如何选择随机代理以及用户代理,拆分代理然后将其发送到个人资料?

def change():

 fi  = open("C:\\UsersDesktop\\text_file1.txt","r")
 file1 = random.choice(fi.readlines())
 print(file1)

 fi2 =  open("C:\\Users\\Desktop\\text_file2.txt","r")
 file2 = fi2.read().splitlines()

 for p, a in zip(file, file2):
      print(p)
      IP,PORT = urls.strip().split(':')
      print(file1)
      try:
           print("Trying proxy {0}" .format(p))
           print("Brwoser Agent {0}" .format(a))
           profile = webdriver.FirefoxProfile()
           profile.set_preference("network.proxy.type", 1)
           profile.set_preference("network.proxy.http", IP)
           profile.set_preference("network.proxy.http_port", int(PORT))
           profile.set_preference("network.proxy.ssl", IP)
           profile.set_preference("network.proxy.ssl_port", int(PORT))
           profile.set_preference("network.proxy.ftp", IP)
           profile.set_preference("network.proxy.ftp_port", int(PORT))

    profile.set_preference("general.useragent.override",'{0}'.format(a))
           profile.update_preferences()
           driver = webdriver.Firefox(firefox_profile=profile)
           #driver.set_window_position(-2000, 0)
           driver.get("https://www.whatismyiaddress.com")
           print('Program will pause for 1 min 40 sec')
           time.sleep(100)
           driver.quit()

      except:
           print('This is not working : %s' % p)
           print("next try in 5 seconds")
           time.sleep(5)
           driver.quit()


 print('Nothing left to try')

2 个答案:

答案 0 :(得分:1)

我将提供一个关于输出随机列表的示例,其中包含一些解释。

from random import shuffle

lineList = open("test.txt", "r").readlines()
shuffle(lineList)

for line in lineList:
    print(line)

首先,我们需要从随机库中导入shuffle方法。

from random import shuffle

接下来,我们需要读取整个文件并将其存储到变量中。

lineList = open("test.txt", "r").readlines()

我们将使用readlines()方法,因为这将为我们提供一个列表,我们可以将它存储在lineList变量中以便稍后进行操作。

要随机化列表中项目的顺序,我们将使用我们之前在程序中导入的shuffle方法。

shuffle(lineList)

最后,我们将使用for循环遍历列表中的每一行。然后我们可以按照我们认为合适的方式操作该行(在本例中,我只是输出变量)。

for line in lineList:
    print(line)

重要的是要注意,每次运行该程序时,它都会创建一个不同的随机列表。如果您想要一个随机列表,但在每次执行程序时使用相同的随机化,则必须设置应用程序中使用的随机数随机数生成器的种子。有关种子和随机化如何运作的更多信息,请参见here

答案 1 :(得分:0)

到目前为止,我理解了这个问题:

import random
with open('l.txt', 'r') as f:
    res = f.readlines()

text_list = list(res)

for r in range(0, len(text_list)):
    random.shuffle(text_list)
    line = text_list.pop()
    print (len(text_list))
    print (line)