How to Open Web Browser URL Link from Python Script

By: DevNami

0   0   39290

Uploaded on 02/14/2014

Python program to open an URL in browser using script. Learn how to open a web browser and then open Google or any other website in new tab. This script is very simple and you can extend it for other web searching and scraping related automation tasks as well.

Comments (3):

By anonymous    2017-09-20

The webbrowser module looks promising: https://www.youtube.com/watch?v=jU3P7qz3ZrM

import webbrowser
webbrowser.open('http://google.co.kr', new=2)

Original Thread

By anonymous    2018-01-07

I am currently trying make a python script which opens a URL in web browser and now I am facing a error that NameError: name 'song' is not defined

import webbrowser

class Halsey:
    def__init__(self):
        self.song = song

    def Badland():
        print(" 1.Gasloine" 
        "2.castle" 
        "3.hold me down "
        "4.control")
        song =int(input("Plase select a number from above list"))

if song == 1 :

    url="https://www.youtube.com/watch?v=jU3P7qz3ZrM";

    webbrowser.open(url,new=0)

Original Thread

By anonymous    2018-01-07

Well, your song variable visible only in method Badland of your class. So you can use this variable in the same method where you defined it, like this:

import webbrowser

class Halsey:

    SONGS = (
        ("Gasloine", "https://www.youtube.com/watch?v=jU3P7qz3ZrM"),
        ("Castle", "url2"),
        ("Hold me down ", "url3"),
        ("Control", "url4"),
    )

    def __init__(self):
        for i, song_name in enumerate(self.SONGS, 1):
            print("{}. {}".format(i, song_name[0]))

        song = int(input("Plase select a number from above list: "))
        url = self.SONGS[song - 1][1]
        webbrowser.open(url, new=0)

... or you can return user's input from class method and then use it, like this:

class Halsey:

    SONGS = (
        ("Gasloine", "https://www.youtube.com/watch?v=jU3P7qz3ZrM"),
        ("Castle", "url2"),
        ("Hold me down ", "url3"),
        ("Control", "url4"),
    )

    def get_user_input():
        for i, song_name in enumerate(self.SONGS, 1):
            print("{}. {}".format(i, song_name[0]))

        return int(input("Please select a number from above list: "))

instance = Halsey()
users_choice_int = instance.get_user_input()
url = self.SONGS[song - 1][1]
webbrowser.open(url, new=0)

Also, you can save your variable in class attribute: self.song = int(input(...) and after that you will be able to access it inside class methods by self.song, or outside your class by instance.song.

Note: don't forget about potential invalid user input, you can wrap your song = int(input... in try/except.

Good luck!

Original Thread

Popular Videos 543

Submit Your Video

If you have some great dev videos to share, please fill out this form.