algoProg
algoProg

Reputation: 728

Python 3.5 urllib won't open webpage in browser

I tried following code in VS2015, Eclipse and Spyder:

import urllib.request
with urllib.request.urlopen('https://www.python.org/') as response:
    html = response.read()

In call cases it won't open the webpage in the browser. I am not sure what is the problem. Debug won't help. In VS2015 the program exists with code 0 which I suppose means successful.

Upvotes: 3

Views: 4341

Answers (2)

Deepak Joshi
Deepak Joshi

Reputation: 329

urllib 

is a module that is used to send request to web pages and read its contents.

Where as:

webbrowser

is used to open the desired url.

It can used as follows:

import webbrowser

webbrowser.open('http://docs.python.org/lib/module-webbrowser.html')

which usually re-uses existing browser window.

To open in new window:

webbrowser.open_new('http://docs.python.org/lib/module-webbrowser.html')

To open in new tab:

webbrowser.open_new_tab('http://docs.python.org/lib/module-webbrowser.html')

To access via command line interface:

$ python -m webbrowser -t "http://www.python.org"
-n: open new window
-t: open new tab

Here is python documentation for webbrowser:

python 3.6

python 2.7

Upvotes: 2

HeyYO
HeyYO

Reputation: 2073

You are using wrong library for the job. urllib module provides functions to send http requests and capture the result in your program. It has nothing to do with a web browser. What you are looking for is the webbrowser module. Here is an example:

import webbrowser
webbrowser.open('http://google.com')

This will show the web page in your browser.

Upvotes: 6

Related Questions