在Python中使用Selenium单击具有相同类名称的所有元素

问题描述:

我试图单击网页上的所有“like”按钮。我知道如何点击其中的一个,但我希望能够点击它们。他们具有相同的类名,但具有不同的ID。在Python中使用Selenium单击具有相同类名称的所有元素

我是否需要创建某种列表并告诉它单击列表中的每个项目?有没有写“点击全部”的方法?

这里是我的代码是什么样子(我删除了登录密码):

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' 

我知道我不能在列表上点击,因为它不是一个单一的对象,但我不知道如何否则我会去做这件事。

非常感谢您的帮助。

+0

有人在java上回答了类似的问题,但我不知道如何将其转换为Python或者甚至可能。 http://stackoverflow.com/questions/15537930/getting-list-of-items-inside-div-using-selenium-webdriver –

+0

我的解决方案没有解决问题吗? –

这是不幸的,你得到了整个的两半,你不能通过id找到多个元素,因为ID对于单个元素是唯一的。

因此通过与元素相结合的类你的ID使用迭代法,并查找来获得:

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() 

我强烈怀疑这会为你工作。请告诉我,如果没有。

+0

非常感谢您的回复!它工作完美。我不知道你只能使用find_id方法找到一个元素。 –