gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:58:30 25 4
gpt4 key购买 nike

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

我是否需要创建某种列表并让它点击列表中的每一项?有没有办法写“click all”?

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

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'

我知道我不能点击一个列表,因为它不是一个单一的对象,但我不知道否则我会怎么做。

非常感谢您的帮助。

最佳答案

不幸的是,你得到了整体的两半,你无法通过 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()

我强烈怀疑这对您有用。如果没有请告诉我。

关于python - 在 Python 中使用 Selenium 单击具有相同类名的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31349788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com