Search code examples
opencvpython-3.7os.systempython-webbrowser

How to open websites in background and then close without interrupting flow of program using python?


I want to open a particular video in the background using python. For that, I have done the following coding

 chrome= "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
 webbrowser.get(chrome).open_new("https://www.youtube.com/watch?v=AFNUeUed8Ro&ab_channel=NDTV")
 time.sleep(4)
 os.system("taskkill /im chrome.exe /f")**

but after opening the URL program does not continue until I manually close the site. And if I beforehand open the chrome browser all works well. But that is not what I want.

I want to open it in the background because I only need audio as my project is for blind people's entertainment which opens sites using gestures only then close using the same.


Solution

  • I suggest you use Selenium instead of Webbrowser package as it has more functionality.

    Install Selenium package using

    pip install selenium
    

    Download Chrome webdriver which matches your version of Chrome from

    https://sites.google.com/a/chromium.org/chromedriver/downloads

    Place the driver .exe file where you python script is located

    Try this script

    import selenium
    import time
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    browser = webdriver.Chrome()
    wait = WebDriverWait(browser, 3)
    visible = EC.visibility_of_element_located
    
    browser.get('https://www.youtube.com/watch?v=AFNUeUed8Ro&ab_channel=NDTV')
    wait.until(visible((By.ID, "video-title")))
    browser.find_element_by_id("video-title").click()
    browser.minimize_window()
    time.sleep(7)
    browser.quit()
    

    Don't use time.sleep() in Opencv capture loop because it blocks the capture. If you want to use time delays consider using separate thread. Look at

    https://www.tutorialspoint.com/python/python_multithreading.htm