[英]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.