What module for opening links in python?

Viewed 423

I mean, how am I supposed to do something like this, when I click a button, a browser opens, on the page it url gives? My guess is that a module is needed here, unless it can be done in the Tkinter module, because that's where I want this button (hyperlink, as in html)

2 Answers

Try using the webbrowser module. You can have a look at this link for more information-https://docs.python.org/2/library/webbrowser.html

The webbrowser module provides a high-level interface to allow displaying Web-based documents to users. Under most circumstances, simply calling the open() function from this module will do the right thing.

Under Unix, graphical browsers are preferred under X11, but text-mode browsers will be used if graphical browsers are not available or an X11 display isn’t available. If text-mode browsers are used, the calling process will block until the user exits the browser.

If the environment variable BROWSER exists, it is interpreted to override the platform default list of browsers, as an os.pathsep-separated list of browsers to try in order. When the value of a list part contains the string %s, then it is interpreted as a literal browser command line to be used with the argument URL substituted for %s; if the part does not contain %s, it is simply interpreted as the name of the browser to launch. 1

For non-Unix platforms, or when a remote browser is available on Unix, the controlling process will not wait for the user to finish with the browser, but allow the remote browser to maintain its own windows on the display. If remote browsers are not available on Unix, the controlling process will launch a new browser and wait.

The script webbrowser can be used as a command-line interface for the module. It accepts a URL as the argument. It accepts the following optional parameters: -n opens the URL in a new browser window, if possible; -t opens the URL in a new browser page (“tab”). The options are, naturally, mutually exclusive.

What about using webbrowser module:

import webbrowser

url = "https://google.com"
webbrowser.open(url,new=1) #If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible.

To open url in a new window of the default browser, if possible, otherwise, open url in the only browser window:

webbrowser.open_new(url)

To open url in a new page (“tab”) of the default browser, if possible, otherwise equivalent to open_new():

webbrowser.open_new_tab(url)

This shows, different ways to open the url specified. Easy as that.

If any doubts, do let me know :D

(Added this answer, because the below answer does not include any code)

Cheers

Related