Search code examples
pythonpython-webbrowser

Open tabs using Python script


I'm learning Python and I'm trying to create my own script to automate stuff at work. I'm trying to open a web browser (no matter which one) with a default url and 2 or more tabs with different urls. I tried open_new(), open(), open_new_tab() but it doesn't work. It opens a browser (first url) and when I close its window then opens the second url in a new window.

def open_chrome():
   url = 'www.amazon.com'
   url2 = 'www.google.com'
   browser = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'

   webbrowser.get(browser).open_new(url)
   time.sleep(2)
   webbrowser.get(browser).open_new_tab(url2)

open_chrome()

Solution

  • webbrowser.open(foo, 2)
    

    May solve your problem.

    Edit: As per our discussion in the comments, try this solution:

    import webbrowser
    import time
    
    def open_chrome():
       url = 'www.amazon.com'
       url2 = 'www.google.com'
       browser = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
    
       webbrowser.get(browser)
       #You can do webbrowser.open(url, 0) if you want to open in the same window, 1 is a new window, 2 is a new tab. Default behaviour opens them in a new tab anyway.
       #See https://docs.python.org/2/library/webbrowser.html
       webbrowser.open(url) 
       #time.sleep(2) -- Commented this out as I didn't find it neccessary.
       webbrowser.open(url2)
    
    open_chrome()