1

How can I open a URL with my default webbrowser in the background without changing window focus?

In other words I want to stay in the terminal while opening the webbrowser.

I have tried the webbrowser module without success.

Python 3.8.1 (default, Jan 17 2020, 10:45:46)
>>> import webbrowser
>>> webbrowser.open("https://stackoverflow.com", autoraise=False)

Is there an easy way to solve this or is it a Mac OS problem?

Rickard Körkkö
  • 548
  • 3
  • 10

3 Answers3

1

instead of webbrower module you can try:

import subprocess

url = subprocess.getoutput("google-chrome-stable https://stackoverflow.com")
url
Kaustubh Ghole
  • 537
  • 1
  • 10
  • 25
  • Thanks. I get this error though `'/bin/sh: google-chrome-stable: command not found`. I would also prefer if it used my default webbrowser as this may change. – Rickard Körkkö Jan 20 '20 at 08:27
1

You should use selenium and download chrome driver instead and add headless option for your chrome browser.

from selenium import webdriver
import time


chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-notifications')
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(executable_path="/Users/mypc/Downloads/chromedriver-2",options=chrome_options)

# or you can use Chrome(executable_path="/usr/bin/chromedriver")

driver.get("https://www.instagram.com/accounts/login/")
time.sleep(2)
Sasho Ristovski
  • 147
  • 1
  • 7
0

You can use subprocess.check_output and pass terminal command as an array:

in mac terminal open command will do the work for you

import subprocess
#subprocess.check_output(['ls','-l']) #all that is technically needed...
#in open documention in terminal you can use --hide to run in background
print subprocess.check_output(['open','http://google.com/','--hide'])
Farhoud
  • 91
  • 6
  • It does open the URL but not in the background. – Rickard Körkkö Jan 20 '20 at 08:30
  • 2
    @Farhoud Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – Ismael Padilla Jan 20 '20 at 11:12
  • Need to upgrade to python 3 – Tiago Rangel May 15 '22 at 19:19