BGFX
BGFX

Reputation: 23

Using Selenium in Python to click all buttons in a webpage

I am trying to click on all the buttons on a webpage. I'd like to be able to click them all. webpage i can click on one of them by using css selector

browser.find_element_by_css_selector('li.clickable_area:nth-child(1) > div:nth-child(3)').click()

these are the css selector for the 5 buttons

the 5 buttons follow this pattern:

Button 1: li.clickable_area: nth - child(1) > div:nth - child(3)

Button 2: li.clickable_area: nth - child(2) > div:nth - child(3)

Button 3: li.clickable_area: nth - child(3) > div:nth - child(3)

Button 4: li.clickable_area: nth - child(4) > div:nth - child(3)

Button 5: li.clickable_area: nth - child(5) > div:nth - child(3)

How i can i click them all using css selector without writing a code for each one?

Upvotes: 2

Views: 3811

Answers (2)

Muzzamil
Muzzamil

Reputation: 2881

Make a list of all buttons and iterate it. Please try below code:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

    buttons=WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.clickable_area > div:nth-child(3)")))
        for x in range(0,len(buttons)):
            if buttons[x].is_displayed():
                buttons[x].click()

OR

buttons=WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[contains(text(), 'Button ')]")))
        for x in range(0,len(buttons)):
           button = WebDriverWait(driver, 50).until(EC.presence_of_element_located((By.XPATH, "//div[contains(text(), 'Button ')]")))
                   button.click()

Upvotes: 0

supputuri
supputuri

Reputation: 14135

You can use the loop to iterate through and click on the number of buttons.

number_of_buttons = 5
for x in range(number_of_buttons):
    button = browser.find_element_by_css_selector("li.clickable_area:nth-child(" + str(x+1) + ") > div:nth-child(3)")
    button.click()

If you want to click on all the li(x) > div:nth-child(3) then you can use the below.

number_li_elems=len(WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.clickable_area"))))
for x in range(number_li_elems):
    # you have to get the element by index every time, otherwise you will get StaleElement Exception
    button = browser.find_element_by_css_selector("li.clickable_area:nth-child(" + str(x+1) + ") > div:nth-child(3)")
    button.click()

Upvotes: 1

Related Questions