Using Selenium in Python to click on all elements with the same class name

I am trying to click all the "like" buttons on a web page. I know how to click on one of them, but I wish they could be clickable. They have the same class name but different identifiers.

Do I need to create some kind of list and tell him to click on each of the items in the list? Is there a way to write "click all"?

This is what my code looks like (I removed the login code):

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
browser.set_window_size(650, 700)
browser.get('http://iconosquare.com/viewer.php#/tag/searchterm/grid')

mobile = browser.find_element_by_id('open-menu-mobile')
mobile.click()
search = browser.find_element_by_id('getSearch')
search.click()
search.send_keys('input search term' + Keys.RETURN)

#this gets me to the page I want to click the likes
fitness = browser.find_element_by_css_selector("a[href*='fitness/']")
fitness.click()

#here are the different codes I've tried to use to click all of the "like buttons"

#tried to create a list of all elements with "like" in the id and click on all of them.  It didn't work.
like = browser.find_elements_by_id('like')
for x in range(0,len(like)):
    if like[x].is_displayed():
        like[x].click()

#tried to create a list by class and click on everything within the list and it didn't work.
like = browser.find_elements_by_class_name('like_picto_unselected')
like.click()

AttributeError: 'list' object has no attribute 'click'

      

I know I cannot click on the list because it is not one object, but I have no idea how it would have happened otherwise.

Your help is greatly appreciated.

+3


source to share


1 answer


This is unfortunate, you have two halves of a whole, you cannot find multiple elements by id, because the id is unique for one element.

so combine the iterative method you use with id and find elements with classes to get:



like = browser.find_elements_by_class_name('like_picto_unselected')
for x in range(0,len(like)):
    if like[x].is_displayed():
        like[x].click()

      

I strongly suspect this will work for you. Please tell me if not.

+6


source







All Articles