如何在Selenium中随机点击鼠标(从不相同的元素)?

问题描述:

我想随机点击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() 

如果你想点击随机元素(从随机索引列表元素)你可以尝试

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