相同类名但不是同级别的最后一个元素_在Python中使用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'

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

非常感谢您的帮助.

最佳答案 这很不幸,你有两半的整体,你找不到id的多个元素,因为ID对于单个元素是唯一的.

所以将你使用的迭代方法与id和使用类的元素的find相结合,得到:

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值