2017-08-28 453 views
1

我想隨機點擊Windows 10 python 3.下面的代碼工作,除非它不是隨機點擊元素。它也以一種可笑的速度點擊。爲了試圖阻止這個,我添加了time.sleep(3),但是這往往會使它失敗,並且給出一個沒有這個睡眠命令就不存在的錯誤。所有元素似乎已經加載。看到錯誤信息與睡眠:https://ibb.co/cUYL45如何在Selenium中隨機點擊鼠標(從不相同的元素)?

 import time 
     from selenium import webdriver 
     from random import randint 

     driver = webdriver.Chrome(executable_path=r'C:\Brother\chromedriver.exe') 
     driver.set_window_size(1024, 600) 
     driver.maximize_window() 

     time.sleep(4) 

     driver.get('https://www.unibet.com.au/betting#drill-down/football') 


     time.sleep(10) 
     links = driver.find_elements_by_css_selector('.KambiBC-drill-down-navigation__toggle') 
    #Not randomising?? 
     l = links[randint(0, len(links)-1)] 
     for l in links: 
      l.click() 
#Tends to give error when I have a sleep command but it's goes way to fast not to have it. 
#All elements have already loaded so explicit not needed.. 
      time.sleep(5) 
      ... 


     time.sleep(5) 



     driver.close() 

回答

0

如果你想點擊隨機元素(從隨機索引列表元素)你可以嘗試

l = links[randint(0, len(links)-1)] 
l.click() 

,而不是

l = links[randint(0, len(links)-1)] 
for l in links: 
    l.click() 

請注意0​​在l = links[randint(0, len(links)-1)]lfor l in links是不同的變量

如果你想每次從下拉新option元素點擊,你可以試試下面:

from random import shuffle 
from selenium.webdriver.support.ui import WebDriverWait as wait 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support import expected_conditions as EC 
from selenium import webdriver as web 

driver = web.Chrome() 
driver.get('https://ubet.com/sports/soccer') 

options = driver.find_elements_by_xpath('//select[./option="Soccer"]/option') 

# Get list of inetegers [1, 2, ... n] 
indexes = [index for index in range(len(options))] 
# Shuffle them 
shuffle(indexes) 
for index in indexes: 
    # Click on random option 
    wait(driver, 10).until(
     EC.element_to_be_clickable((By.XPATH, '(//select[./option="Soccer"]/option)[%s]' % str(index + 1)))).click() 
+2

它只是它完成循環,並轉移到腳本的下一部分之前點擊約3元。它似乎並沒有循環 – Tetora

+2

你能澄清一下你想如何點擊這些元素嗎?你想對'n = len(鏈接)'的隨機元素進行'n'點擊嗎? – Andersson

+0

我想以隨機順序單擊.KambiBC-drill-down-navigation__toggle元素(37個元素+每天不同)的所有內容。所以理想情況下,同樣的元素不會被點擊兩次。這是否澄清? – Tetora

相關問題