mardi 7 mars 2023

How to click a list of checkboxes randomly using Selenium with Python?

I want Selenium to click multiple checkboxes on this WebPage randomly, i.e. go to the page and each time click some different checkboxes. How can I do this?

This is my current solution:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager


@pytest.fixture(scope='function')
def driver():
    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.maximize_window()
    yield driver
    driver.quit()

def mult_elements_visibility(self, locator, timeout=5):
return WebDriverWait(self.driver,timeout).until(EC.visibility_of_all_elements_located(locator))

def go_to_element(self, element):
return self.driver.execute_script('arguments[0].scrollIntoView();', element)

#let's open the page
driver.get('https://demoqa.com/checkbox')

#let's expand the list 
def open_full_list(self):
    WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located(By.CSS_SELECTOR, 'button[title="Expand all"]')).click()

#let's click random checkboxes in that list
def click_random_checkbox(self):

    #let's create a list of necessary elements
    item_list = mult_elements_visibility(By.CSS_SELECTOR, 'span[class="rct-title"]')

    #let's pick a random item from that list
    random_item = item_list[random.randint(1,15)]

    #let's iterate over that random numbers clicking its items:
    i = 5
    for i in random_item:
        go_to_element(random_item)
        random_item.click()
        next(random_item)
        i -= 1

It feels like I miss something in the idea itself and definitely a lot in the realisation of that idea




Aucun commentaire:

Enregistrer un commentaire