You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium爬虫窗口数量控制需求求助:超5个等待,不足则继续

解决方案

要实现窗口数量超过5个时等待、少于5个时继续爬取的逻辑,你可以在每次准备打开新窗口前加入窗口数量检查与等待机制。以下是修改后的完整代码:

def run_code():
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from webdriver_manager.chrome import ChromeDriverManager
    import time

    options = Options()
    options.add_experimental_option("detach", True) 
    options.add_experimental_option("excludeSwitches", ["enable-logging"]) 

    driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)

    driver.get("https://goodday.com/bbs/")
    elements = driver.find_elements('xpath', '//*[@id="list-body"]/li/div[1]/a')[:-1]

    for link in elements:
        # 检查当前窗口数量,超过或等于5则进入等待
        while len(driver.window_handles) >= 5:
            print(f"当前窗口数{len(driver.window_handles)},超过上限,等待窗口关闭...")
            time.sleep(2)  # 每2秒检查一次
        
        link = link.get_attribute("href")
        driver.execute_script('window.open("/");')  

        driver.switch_to.window(driver.window_handles[-1]) 
        driver.get(link)
        driver.implicitly_wait(30)
        time.sleep(1)

        driver.switch_to.window(driver.window_handles[0])  
        time.sleep(2)

        opened_window = len(driver.window_handles)
        print(f"opened_window length : {opened_window} opened.")


if __name__ == "__main__":
    run_code()

关键修改说明

  • 在每次打开新窗口前,加入while循环检查当前窗口数量:只要窗口数≥5,就持续等待并打印提示信息,每2秒重新检查一次
  • 等待逻辑会一直执行,直到窗口数量降到5以下,才会继续执行打开新窗口的爬取操作
  • 保留了你原有的窗口切换、页面访问等核心逻辑,仅新增窗口数量管控部分

内容的提问来源于stack exchange,提问作者Happy_Man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:05:24