Python webbrowser.open() to open Chrome browser
Asked Answered
W

21

74

According to the documentation http://docs.python.org/3.3/library/webbrowser.html it's supposed to open in the default browser, but for some reason on my machine it opens IE. I did a google search and I came across an answer that said I need to register browsers, but I'm not sure how to use webbrowser.register() and the documentation doesn't seem to be very clear. How do I register Chrome so that urls I pass to webbrowser.open() open in Chrome instead of IE?

Weatherboarding answered 17/3, 2014 at 0:50 Comment(1)
I managed to fix it just by having "https://" in front of the URL and it worked properly. When I didn't it opened in Edge.Gresham
T
140

You can call get() with the path to Chrome. Below is an example - replace chrome_path with the correct path for your platform.

import webbrowser

url = 'http://docs.python.org/'

# MacOS
chrome_path = 'open -a /Applications/Google\ Chrome.app %s'

# Windows
# chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'

# Linux
# chrome_path = '/usr/bin/google-chrome %s'

webbrowser.get(chrome_path).open(url)
Tallis answered 22/6, 2014 at 17:28 Comment(6)
how would I open chrome in kiosk mode for linux with this?Excelsior
NOT working. it execute chrome but not exiting. How to execute the chrome and make sure its opened then move to next actions?Wavemeter
Linux file access permissions may prevent Google Chrome from loading, e.g. user access vs. root access. I have two versions of Chrome installed. One for root and one for user.Relinquish
@Christian do you know why "Path/file.exe %s" works but not this: (r"Path/file.exe") or str(Path/file.exe) ?Fidellas
what is the difference between webbrowser library and seleniumDraghound
I have done it and yes it displays any web when play in console but it is not pop up when execute under task schedulers. You have any idea the reason behind it..Loria
P
37

In the case of Windows, the path uses a UNIX-style path, so make the backslash into forward slashes.

webbrowser.get("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s").open("http://google.com")

See: Python: generic webbrowser.get().open() for chrome.exe does not work

Procrustes answered 7/7, 2015 at 7:40 Comment(6)
this helped me immenselyKitti
NOT working. It execute the Chrome but then it does not exit.Wavemeter
@zacharias any idea why "Path/browser.exe %s" works but not this: (r"Path/browser.exe") or (str(Path/browser.exe))?Fidellas
don't work: webbrowser.get("path") webbrowser.open("url") Work: webbrowser.get("path").open("url") (any idea why?)Fidellas
Thanks! It worked :) Can you tell me how can I get response aswell from browser in python? In my case Its just simple JSON in responseAffinitive
its working nicely in my machine but the web does not pop up when execute under task scheduler. Any idea what went wrong???Loria
C
22
import webbrowser 
new = 2 # open in a new tab, if possible

# open a public URL, in this case, the webbrowser docs
url = "http://docs.python.org/library/webbrowser.html"
webbrowser.get(using='google-chrome').open(url,new=new)

you can use any other browser by changing the parameter 'using' as given in a link

Crystalcrystalline answered 24/4, 2017 at 21:21 Comment(2)
For open a new tab you can use webbrowser.get(using='google-chrome').open_new_tab(url)Ironbark
This solution throws an exception 'could not locate runnable browser'Happygolucky
A
6

you can also use this:

import webbrowser

chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
url = "http://docs.python.org/"

webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path))
webbrowser.get('chrome').open_new_tab(url)
Altar answered 16/3, 2021 at 17:22 Comment(1)
This absolutely worked for me. Thanks! Would you mind explaining a little bit about the usage of "webbrowser.register"? It's hard to understand what role "None" and "BackgroundBrowser".Shoelace
D
4

Please check this:

import webbrowser
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
webbrowser.get(chrome_path).open('http://docs.python.org/')
Deberadeberry answered 19/6, 2019 at 10:45 Comment(0)
H
4

worked for me to open new tab on google-chrome:

import webbrowser

webbrowser.open_new_tab("http://www.google.com")
Humoresque answered 24/9, 2019 at 2:2 Comment(1)
Me too, but only after I made Chrome my default browser.Cioban
C
3

Here's a somewhat robust way to get the path to Chrome.

(Note that you should do this only if you specifically need Chrome, and not the default browser, or Chromium, or something else.)

def try_find_chrome_path():
    result = None
    if _winreg:
        for subkey in ['ChromeHTML\\shell\\open\\command', 'Applications\\chrome.exe\\shell\\open\\command']:
            try: result = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, subkey)
            except WindowsError: pass
            if result is not None:
                result_split = shlex.split(result, False, True)
                result = result_split[0] if result_split else None
                if os.path.isfile(result):
                    break
                result = None
    else:
        expected = "google-chrome" + (".exe" if os.name == 'nt' else "")
        for parent in os.environ.get('PATH', '').split(os.pathsep):
            path = os.path.join(parent, expected)
            if os.path.isfile(path):
                result = path
                break
    return result
Cholent answered 26/5, 2019 at 8:10 Comment(4)
Your method looks promising but your answer is incomplete. What Python libraries are you importing to get your method to work? I get an error message: "NameError: name '_winreg' is not defined".Galan
@RichLysakowskiPhD: docs.python.org/2/library/_winreg.htmlCholent
Thanks for your superfast answer. You replied within 2 minutes! The following imports were missing in your example: import os, winreg, shlex. And then the only other thing needed was to change the variable "_winreg" to "winreg" since in Python 3 the name was changed to remove the leading underscore.Galan
Here is the updated URL for Python 3.8 to 3.10 production versions: docs.python.org/3.8/library/winreg.html OR docs.python.org/3.10/library/winreg.htmlGalan
F
2

Made this for a game I play, it was relevant so i'm leaving it. It's real simple. Grabs the value from platform.system. Checks it against known values for different operating systems. If it finds a match it sets the chrome path for you. If none are found it opens default browser to your link. Hope its useful to someone.

import time
import os
import webbrowser
import platform

user_OS = platform.system()
chrome_path_windows = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
chrome_path_linux = '/usr/bin/google-chrome %s'
chrome_path_mac = 'open -a /Applications/Google\ Chrome.app %s'
chrome_path = ''
game_site_link = 'https://www.gamelink'

if user_OS == 'Windows':
    chrome_path = chrome_path_windows
elif user_OS == 'Linux':
    chrome_path = chrome_path_linux
elif user_OS == 'Darwin':
    chrome_path = chrome_path_mac
elif user_OS == 'Java':
    chrome_path = chrome_path_mac
else:
    webbrowser.open_new_tab(game_site_link)

webbrowser.get(chrome_path).open_new_tab(game_site_link) 

I actually changed it some more here it is updated since I am still working on this launcher

import time
import webbrowser
import platform
import subprocess
import os
import sys

privateServerLink = 'https://www.roblox.com/games/2414851778/TIER-20-Dungeon-Quest?privateServerLinkCode=GXVlmYh0Z7gwLPBf7H5FWk3ClTVesorY'
userBrowserC = input(str("Browser Type: chrome, opera, iexplore, firefox : "))
userSleepTime = int(input("How long do you want it to run?"))
if userBrowserC == 'opera':
    userBrowserD = 'launcher.exe'
else:
    userBrowserD = userBrowserC

if userBrowserC == "chrome":
    taskToKill = "chrome.exe"
else:
    taskToKill = "iexplore.exe"

if userBrowserC == 'chrome' and platform.system() == 'Windows':
     browserPath = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
elif userBrowserC == 'chrome' and platform.system() == 'Linux':
    browserPath = '/usr/bin/google-chrome %s'
elif userBrowserC == 'chrome' and platform.system() == 'Darwin' or 
platform.system() == 'Java':
    browserPath = 'open -a /Applications/Google\ Chrome.app %s'
elif userBrowserC == 'opera' and platform.system() == 'Windows':
    browserPath = 'C:/Users/'+ os.getlogin() +'/AppData/Local/Programs/Opera/launcher.exe'
elif userBrowserC == 'iexplore' and platform.system() == 'Windows':
    browserPath = 'C:/Program Files/internet explorer/iexplore.exe %s'
elif userBrowserC == 'firefox' and platform.system() == 'Windows':
    browserPath = 'C:/Program Files/Mozilla Firefox/firefox.exe'
else:
    browserPath = ''
while 1 == 1:   
    subprocess.Popen('SynapseX.exe')
    time.sleep(7)
    webbrowser.get(browserPath).open_new_tab(privateServerLink)
    time.sleep(7)  
    os.system('taskkill /f /im '+taskToKill)
    time.sleep(userSleepTime)
Fritzie answered 22/11, 2019 at 6:48 Comment(0)
S
2

One thing I noticed and ran into problems with were the slashes, in Windows you need to have two of them in the path an then this works fine.

import webbrowser
chrome_path = "C://Program Files (x86)//Google//Chrome//Application//Chrome.exe %s"
webbrowser.get(chrome_path).open("https://github.com/")

This at least works for me

Scrutator answered 11/1, 2021 at 7:8 Comment(0)
M
2

Uhh...Hey You can Quickly Solve this Issue By adding https:// Lemme Show it Below -

import webbrowser
URL = "https://www.python.org"
webbrowser.open(URL)

enter image description here

Miscalculate answered 3/3, 2022 at 12:56 Comment(0)
A
1

Worked for me in windows

Put the path of your chrome application and do not forget to put th %s at the end. I am still trying to open the browser with html code without saving the file... I will add the code when I'll find how.

import webbrowser
chromedir= "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
webbrowser.get(chromedir).open("http://pythonprogramming.altervista.org")

>>> link to: [a page from my blog where I explain this]<<<

Audacity answered 19/4, 2018 at 5:15 Comment(0)
L
1

If you have set the default browser in windows then you can do this:

open_google = webbrowser.get('windows-default').open('https://google.com')

// OR

open_google = webbrowser.open('https://google.com')
Liaoning answered 5/7, 2019 at 14:58 Comment(1)
It uses webbrowser module so don't forget to import it by:import webbrowser Remember, you can also do this using selenium.Liaoning
F
1
if sys.platform[:3] == "win":
    # First try to use the default Windows browser
    register("windows-default", WindowsDefault)

    # Detect some common Windows browsers, fallback to IE
    iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
                            "Mozilla Firefox\\FIREFOX.EXE")
    for browser in ("firefox", "firebird", "seamonkey", "mozilla",
                    "netscape", "opera", iexplore):
        if shutil.which(browser):
            register(browser, None, BackgroundBrowser(browser))

100% Work....See line number 535-545..Change the path of iexplore to firefox or Chrome According to your requirement... in my case change path I Mention in the above code for firefox setting......

Fukuoka answered 31/5, 2020 at 8:7 Comment(0)
B
0

Something like this should work:

from selenium import webdriver
#driver = webdriver.Firefox()
driver = webdriver.Chrome()
driver.get("http://www.python.org")
Blackmarketeer answered 23/6, 2017 at 7:35 Comment(2)
Above code will be open the URL in both Firefox and Chrome Browser instead default browser (IE)Blackmarketeer
This isn't even using the same library?Tricrotic
G
0

I found an answer to my own question raised by @mehrdad's answer below. To query the browser path from Windows in a generic way @mehrdad gives a nice short code that uses the Windows Registry, but did not include quite enough context to get it working.

import os 
import winreg
import shlex

def try_find_chrome_path():
    result = None
    if winreg:
        for subkey in ['ChromeHTML\\shell\\open\\command', 'Applications\\chrome.exe\\shell\\open\\command']:
            try: result = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, subkey)
            except WindowsError: pass
            if result is not None:
                result_split = shlex.split(result, False, True)
                result = result_split[0] if result_split else None
                if os.path.isfile(result):
                    break
                result = None
    else:
        expected = "google-chrome" + (".exe" if os.name == 'nt' else "")
        for parent in os.environ.get('PATH', '').split(os.pathsep):
            path = os.path.join(parent, expected)
            if os.path.isfile(path):
                result = path
                break
    return result

print(try_find_chrome_path())

Thanks for the answer @mehrdad !!

Galan answered 29/11, 2019 at 8:36 Comment(0)
S
0

When you have an invalid URL (make sure that the url starts with https:// or http://, and if it doesn't, add it), it generally opens defaults IE.

Streit answered 22/3, 2021 at 21:34 Comment(0)
R
0

believe me or not this is the easiest way to do

webbrowser.open("www.stackoverflow.com")#just remove https:// or http:// and simply add www.something.com

take this url for example

https://something.com

if you will give this url: https://something.com or something.com it will be opened in IE

But if you will type it in this way: www.something.com it will be opened in chrome

You can try this and this will work!

(NOTE: If it has some another suffix like take https://meet.google.com for example if you try to add www. to it, your browser will throw a typo error )

Rebut answered 26/3, 2021 at 11:42 Comment(0)
R
0

I think I found a workaround too

  • Method 1 ( replace / with \ )
...
expression = "https://mcmap.net/q/269359/-python-webbrowser-open-to-open-chrome-browser"

if ("https:" in expression) or ("http:" in expression):
    expression = expression.replace("/", "\\")
    web.open_new_tab(expression.strip())
...
  • Method 2 ( use www as many of u suggested )
...
expression = "www.python.org"

if "www." in expression:
    web.open_new_tab(expression.strip())
...
Rationale answered 11/10, 2021 at 16:20 Comment(0)
G
0

Keep it simple:

I want to be able to launch different browsers, because they have a different default theme and their displays look different on my computer.

Here is an approach that parameterizes the URL string to dynamically create the URL with the browser name "on the fly".

import subprocess

browser_type = "chrome"  # Replace the value with "edge" or "firefox"

location_url = "https://mcmap.net/q/270829/-how-to-open-a-new-default-browser-window-in-python-when-the-default-is-chrome{browser_type}"

command_fstring = f"cmd /c start firefox {location_url} --new-window"

subprocess.Popen(command_string, shell=True)

To give credit where it is due, this is based on the answer by @Sharath on this page: Web browser chrome, can't open URL in new window, keeps opening URL as a tab

Galan answered 21/1, 2023 at 1:33 Comment(0)
O
-1

In Selenium to get the URL of the active tab try,

from selenium import webdriver

driver = webdriver.Firefox()
print driver.current_url # This will print the URL of the Active link

Sending a signal to change the tab

driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

and again use

print driver.current_url

I am here just providing a pseudo code for you.

You can put this in a loop and create your own flow.

I new to Stackoverflow so still learning how to write proper answers.

Optometrist answered 28/6, 2017 at 10:24 Comment(0)
P
-2

at least in Windows it has to be enough and you do not have to take care about path to the browser.

import webbrowser

url = 'https://stackoverflow.com'

webbrowser.open(url)

Note: With the above lines of code, it only opens in windows defualt browser(Microsoft Edge).

Pentarchy answered 11/6, 2017 at 15:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.