社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在Python中使用Selenium单击网页中的所有按钮

bgfx • 6 年前 • 2493 次点击  

我试图点击网页上的所有按钮。我想点击所有的。 webpage 我可以用css选择器点击其中一个

browser.find_element_by_css_selector('li.clickable_area:nth-child(1) > div:nth-child(3)').click()

5个按钮遵循以下模式:

按钮1: li.clickable_area: nth - child(1) > div:nth - child(3)

按钮2: li.clickable_area: nth - child(2) > div:nth - child(3)

按钮3: li.clickable_area: nth - child(3) > div:nth - child(3)

按钮4: li.clickable_area: nth - child(4) > div:nth - child(3)

li.clickable_area: nth - child(5) > div:nth - child(3)

如何使用css选择器单击它们,而不为每一个都编写代码?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55348
文章 [ 2 ]  |  最新文章 6 年前
Muzzamil
Reply   •   1 楼
Muzzamil    6 年前

做一个 list

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

    buttons=WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.clickable_area > div:nth-child(3)")))
        for x in range(0,len(buttons)):
            if buttons[x].is_displayed():
                buttons[x].click()

或者

buttons=WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[contains(text(), 'Button ')]")))
        for x in range(0,len(buttons)):
           button = WebDriverWait(driver, 50).until(EC.presence_of_element_located((By.XPATH, "//div[contains(text(), 'Button ')]")))
                   button.click()
supputuri
Reply   •   2 楼
supputuri    6 年前

您可以使用循环遍历并单击按钮的数量。

number_of_buttons = 5
for x in range(number_of_buttons):
    button = browser.find_element_by_css_selector("li.clickable_area:nth-child(" + str(x+1) + ") > div:nth-child(3)")
    button.click()

如果你想点击所有 li(x) > div:nth-child(3) 那你可以用下面的。

number_li_elems=len(WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.clickable_area"))))
for x in range(number_li_elems):
    # you have to get the element by index every time, otherwise you will get StaleElement Exception
    button = browser.find_element_by_css_selector("li.clickable_area:nth-child(" + str(x+1) + ") > div:nth-child(3)")
    button.click()