Search code examples
pythonselenium-webdriverscreen-scraping

How to click this button with Selenium?


How do I click all buttons on my page if there are 5 of them or more? I need to do this with Selenium.

Element and source screenshot:

HTML content from https://samara.docke.ru/facade/

Here is what I've tried:

find_more_element = driver.find_element(By.CLASS_NAME, 'products-tile__btn')
while True:
    if not driver.find_elements(By.CLASS_NAME, 'products-tile__btn'):
        with open("link_page.html", "w") as file:
            file.write(driver.page_source)
        break

    else:
        actions = ActionChains(driver)
        actions.move_to_element(find_more_element).perform()
        time.sleep(3)

Solution

  • One issue with those buttons is that there are 10 of them on the page but only 2 are visible. So, we'll need to grab all of the buttons, loop through each, check if it's visible, if it is visible then click it. The code below has been tested and works.

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.wait import WebDriverWait
    
    url = 'https://samara.docke.ru/facade/'
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get(url)
    
    wait = WebDriverWait(driver, 10)
    buttons = wait.until(EC.visibility_of_any_elements_located((By.CSS_SELECTOR, "div.products-tile__more")))
    
    for button in buttons:
        if button.is_displayed():
            button.click()