簡體   English   中英

在 Python 中使用 Selenium 單擊網頁中的所有按鈕

[英]Using Selenium in Python to click all buttons in a webpage

我試圖點擊網頁上的所有按鈕。 我希望能夠全部點擊它們。 網頁我可以使用 css 選擇器點擊其中之一

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

這些是 5 個按鈕的 css 選擇器

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)

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

我如何使用 css 選擇器單擊它們而不為每個人編寫代碼?

您可以使用循環遍歷並單擊按鈕數量。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM