Home > Net >  Where is the configuration to open a specific web browser in python?
Where is the configuration to open a specific web browser in python?

Time:01-11

This is a Win10 machine.

I have a file on disk called "test.html". When I run this in a terminal window C:\>test.html my default browser opens, and that is chrome.

Now I do the same in python

C:\> copy con test.py
import webbrowser
webbrowser.open('http://www.python.org')
^Z
    1 file(s) copied.
C:\>python test.py

and Chrome, the default browser opens

But when I take an HTML response from an API call, and do the same webbrowser.open(...) then Internet Explorer opens. Not Edge, not Chrome, but Internet explorer.

How? It's almost as if there is something in the response that tells it "open with IE" except that if do it manually from the command line with C:\>response.html it opens chrome too.

Where is this instruction to open Internet Explorer coming from?

CodePudding user response:

It should use your default browser. Otherwise, it falls back to IE

It appears to use os.startfile() to detect file associations, so running os.startfile('response.html') apparently throws a OSError for you, and you have no other browser installed in the list. Surprisingly, "chrome" nor "edge" is listed there.

Related - https://github.com/python/cpython/pull/11327

Another option you could try is to use something like webbrowser.open("file://c/response.html")

CodePudding user response:

You can try webbrowser.get().

For example, opening a new tab in Google Chrome:

webbrowser.get(using='google-chrome').open_new_tab('https://google.com')

But it is not always possible to get by with .get () alone, and in this case the .register () function comes to the rescue, for example:

import webbrowser
webbrowser.register('Chrome', None, webbrowser.BackgroundBrowser('C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'))
webbrowser.get('Chrome').open_new_tab('google.com')

You can also check these links:

https://docs.python.org/3/library/webbrowser.html http://pymotw.com/2/webbrowser/ https://discourse.world/h/2019/10/10/How-to-open-a-link-in-Python.Working-with-WebBrowser-and-solving-a-problem-with-Internet-Explorer

  •  Tags:  
  • Related