2017-08-16 73 views
-1
foo = ['hello', 'hi', 'sup', 'hey', 'yo'] 
def main(): 
    actions = ActionChains(driver) 

    with open('links.txt', 'r') as f: 
     urls = [] 
     for url in f: 
      rand = random.choice(foo) 
      driver.get(url) 
      time.sleep(3) 
      driver.execute_script("window.scrollTo(0, 200)") 
      time.sleep(1) 
      try: 
       driver.find_element_by_class_name('comment-simplebox-renderer-collapsed-content').click() 
       actions.send_keys(rand) 
       actions.perform() 
       driver.find_element_by_xpath("""//*[@id="comment-simplebox"]/div[3]/div[2]/button[2]""").click() 
       time.sleep(3) 
      except NoSuchElementException: 
       pass 

而是選擇一個隨機字符串我有foo的列表,它不是選取一個隨機字符串的第一次,它只是拿起第一串和第二次增加了一個隨機字符串到。所以它只是將字符串添加到rand變量而不是覆蓋它。我該如何解決這個問題?隨機選擇工作不正常

我試着向上移動rand變量,但沒有奏效。

+4

'random.choice'作品。你的代碼沒有。 'foo'在哪裏申報?一個[mcve]會很好。 –

+1

它在我的程序的頂部被剝落。 –

+2

請編輯問題以顯示'foo'的定義。 – jdehesa

回答

0

這與random.choice無關。

您濫用ActionChains對象:

當你呼籲ActionChains對象上的操作方法,該動作被存儲在ActionChains對象的隊列。當你調用perform()時,事件按照它們排隊的順序被觸發。

每次您撥打actions.send_keys(rand)時,都會在隊列中添加更多操作。調用actions.perform()不會清除操作隊列。

+0

那麼我該如何解決它? –

+0

@DanielCarlsson:執行下列操作之一:(1)完全跳過使用'ActionChains'並執行'driver.find_element_by_whatever(whatever).send_keys(rand)'。 (2)在for循環中移動'actions = ActionChains(driver)'。 (3)在actions.perform()後面調用'actions.reset_actions()'。 (我不確定'reset_actions()'。文檔說它「清除已存儲在遠程端的動作」。這聽起來像是可能會清空動作隊列。如果沒有,選項1和2肯定會奏效。) –