2017-08-25 51 views
0

編輯&添加下面的代碼: 我的主要問題是我在文件1 &用戶代理文件的代理2 &我改變他們都在同一時間,但現在我想隨機選擇改變兩者&送他們個人資料.set_preference(),但它只是隨機選擇1個代理,然後每次都使用同一個代理。請有人幫助我如何選擇隨機代理以及用戶代理,拆分代理,然後將它們發送到配置文件?如何通過文本文件獲取隨機文本和循環,直到它隨機獲取所有文本1?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') 
+1

你需要發佈一些代碼,所以你可以嘗試匿名你擁有和發佈的內容。 – quamrana

回答

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) 
+0

我如何將這段代碼放入我的代碼中? – Rahul

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找到。