Home > Mobile >  How to restart undetected-chromedriver if takes too long to load up?
How to restart undetected-chromedriver if takes too long to load up?

Time:03-12

My undetected-chromedriver usually takes 10-20 seconds to load up, but sometimes, it never loads up (through hours)... Could anyone pls teach me a way to restart it if it takes too long (ex. after x seconds, restart the program). I read about possibly use threading and run 2 functions at the same time to solve this problem, but it was unachievable because I can't start the driver in a function (I can only do so under the "if name == "main":" thing... So far, I was only able to find the way to measure the time it took for my driver to start up using time.time(), but that's all.... I also know the code to re-start my program: "os.execl(sys.executable, sys.executable, *sys.argv)"... Could anyone pls help me?

My code:

import undetected_chromedriver as uc
import time
import os

if __name__ == "__main__":
       start_time_1 = time.time()
       print("initializing driver...")
       opts = uc.ChromeOptions()
       opts.set_capability("detach", True)
       driver = uc.Chrome(version_main=98, options=opts)
       run_time_1 = (time.time() - start_time_1)
       print(f"{run_time_1} seconds had cost so far")

CodePudding user response:

Thanks a lot to @Firaun, below is the correct solution:

import undetected_chromedriver as uc
import time
import os
import signal
import signal
import sys


def signal_handler(signum, frame):
    raise Exception("Timed out!")

signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(10)   # 10 seconds


def initialize():
    print("initializing...")
    opts = uc.ChromeOptions()
    opts.set_capability("detach", True)
    driver = uc.Chrome(version_main=98, options=opts)
    driver.get("https://docs.python.org/3/library/multiprocessing.html#the-process-class")


if __name__ == '__main__':
    try:
        initialize()
    except Exception as msg:
        print("Timed out!")
        os.execl(sys.executable, sys.executable, *sys.argv)


CodePudding user response:

It usually is still stuck in background processing despite not being able to launch. There is no direct method for restart, however you can kill the process from memory using driver.quit() and re-inititate it with driver.get()

import undetected_chromedriver as uc
driver = uc.Chrome()
driver.get('https://cool.no')

if block //if you wanted to wait for some event/time:

driver.quit()
  • Related