I have a question. I'd like to wait for certain conditions. By selenium

Viewed 16

When I crawl using selenium, If the number of open Chrome browser windows is more than 5, I want to wait the program and if the number of windows is less than 5, I want to design the program to continue crawling again. But I can't design this myself with my poor skills. Plese Help me, My bro..

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:
        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()
1 Answers

Before Switching the new window, you can check the no of open browser window and if count more than 5 then wait for that.

noOfOpenWindows=len(driver.window_handles)
if noOfOpenWindows <=5:
   continue
else:
   time.sleep(30) # provide time as you like
Related