如何使用selenium 2024点击这个按钮?

问题描述 投票:0回答:1

如果我的页面上有 5 个或更多按钮,如何单击所有按钮?我需要用 Selenium 来做这个,谢谢!

元素和源截图:

HTML content from https://samara.docke.ru/facade/

这是我尝试过的:

find_more_element = driver.find_element(By.CLASS_NAME, 'products-tile__btn')
            while True:
                if not driver.find_elements(By.CLASS_NAME, 'products-tile__btn'):
                    with open("link_page.html", "w") as file:
                        file.write(driver.page_source)
                    break

                else:
                    actions = ActionChains(driver)
                    actions.move_to_element(find_more_element).perform()
                    time.sleep(3)
python selenium-webdriver screen-scraping
1个回答
0
投票

这些按钮的一个问题是页面上有 10 个按钮,但只有 2 个可见。因此,我们需要抓住所有按钮,循环遍历每个按钮,检查它是否可见,如果可见则单击它。下面的代码已经过测试并且可以工作。

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

url = 'https://samara.docke.ru/facade/'
driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)

wait = WebDriverWait(driver, 10)
buttons = wait.until(EC.visibility_of_any_elements_located((By.CSS_SELECTOR, "div.products-tile__more")))

for button in buttons:
    if button.is_displayed():
        button.click()
© www.soinside.com 2019 - 2024. All rights reserved.