1

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()

2 Answers2

2
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()
dvro
  • 163
  • 7
  • Thanks for your answer but how should I use it on my code? – HelloMyNameIsOscar Jan 05 '20 at 15:58
  • @HelloMyNameIsOscar instead of using webbrowser.get(browser).open_new or open_new_tab try the line I have suggested – dvro Jan 05 '20 at 16:21
  • Bare in mind that my solution will use the default browser of the system. You may have to adjust it to fit your exact requirements. – dvro Jan 05 '20 at 16:24
  • What behaviour are you expecting. Do you want both to open at the same time, or the second one to only open after you close the first one, or the first one to open and wait 2 seconds before opening the next one? – dvro Jan 06 '20 at 10:29
  • I want to open a browser with a website and then one or more tabs with another website (For example: open just one browser with google in the first tab and stackoverflow in the other tab). It doesn't matter if I wait 2 seconds or both are opened at the same time. – HelloMyNameIsOscar Jan 06 '20 at 11:40
  • @HelloMyNameIsOscar I have amended my answer to suit your requirements. Tested and working with Python 3.7 – dvro Jan 06 '20 at 13:25
  • Yes! this is working now but I will do some changes to open only with the browsers that I want. With this code opens the websites in Firefox (my main browser) but it is ok for me. Thank you! – HelloMyNameIsOscar Jan 06 '20 at 14:14
-1
import webbrowser

while True:
    webbrowser.open("https://google.com", new=1)

This should open up some tabs for you. If you get an error then just pip3 install webbrowser in cmd prompt should work.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Shresz
  • 1