How to open a URL in python

PythonBottle

Python Problem Overview


import urllib

fun open():
    return urllib.urlopen('http://example.com')

But when example.com opens it does not render CSS or JavaScript. How can I open the webpage in a web browser?

@error(404)
def error404(error):
    return webbrowser.open('http://example.com')

I am using bottle. Giving me the error:

> TypeError("'bool' object is not iterable",)

Python Solutions


Solution 1 - Python

with the webbrowser module

import webbrowser

webbrowser.open('http://example.com')  # Go to example.com

Solution 2 - Python

import webbrowser  
webbrowser.open(url, new=0, autoraise=True)

Display url using the default browser. If new is 0, the url is opened in the same browser window if possible. 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. If autoraise is True, the window is raised

webbrowser.open_new(url)

Open url in a new window of the default browser

webbrowser.open_new_tab(url)

Open url in a new page (“tab”) of the default browser

Solution 3 - Python

On Windows

import os
os.system("start \"\" https://example.com")

On macOS

import os
os.system("open \"\" https://example.com")

On Linux

import os
os.system("xdg-open \"\" https://example.com")

Cross-Platform

import webbrowser

webbrowser.open('https://example.com')

Solution 4 - Python

You have to read the data too.

Check out : http://www.doughellmann.com/PyMOTW/urllib2/ to understand it.

response = urllib2.urlopen(..)
headers = response.info()
data = response.read()

Of course, what you want is to render it in browser and aaronasterling's answer is what you want.

Solution 5 - Python

You could also try:

import os
os.system("start \"\" http://example.com")

This, other than @aaronasterling ´s answer has the advantage that it opens the default web browser. Be sure not to forget the "http://".

Solution 6 - Python

Here is another way to do it.

import webbrowser

webbrowser.open("foobar.com")

Solution 7 - Python

I think this is the easy way to open a URL using this function

webbrowser.open_new_tab(url)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionshamseeView Question on Stackoverflow
Solution 1 - PythonaaronasterlingView Answer on Stackoverflow
Solution 2 - PythonimpView Answer on Stackoverflow
Solution 3 - PythonabranheView Answer on Stackoverflow
Solution 4 - PythonpyfuncView Answer on Stackoverflow
Solution 5 - PythonSebastian HietschView Answer on Stackoverflow
Solution 6 - PythonDavid OdhiamboView Answer on Stackoverflow
Solution 7 - PythonNamdari HimanView Answer on Stackoverflow