小编典典

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

selenium

我正在尝试单击网页上的所有“喜欢”按钮。我知道如何单击其中之一,但我希望能够全部单击它们。它们具有相同的类名,但ID不同。

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

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

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'

我知道我无法单击列表,因为它不是单个对象,但是我不知道如何处理。

非常感谢您的帮助。


阅读 622

收藏
2020-06-26

共1个答案

小编典典

不幸的是,您只得到了两半,因为ID对于单个元素是唯一的,所以无法通过ID找到多个元素。

因此,将与id一起使用的迭代方法和带有类的find by元素结合起来,可以得到:

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

我强烈怀疑这对您有用。请告诉我是否。

2020-06-26