Search code examples
pythonfile-iopython-webbrowser

Scripting a website-opener


I'm using a python script to take in a file containing a bunch of website URLs and open all of them in new tabs. However, I'm getting an error message when opening the first website: this is what I get:

0:41: execution error: "https://www.pandora.com/ " doesn’t understand the “open location” message. (-1708)

My script thus far looks like this:

import os
import webbrowser
websites = []
with open("websites.txt", "r+") as my_file:
    websites.append(my_file.readline())
for x in websites:
    try:
        webbrowser.open(x)
    except:
        print (x + " does not work.")

My file consists of a bunch of URLs on their own lines.


Solution

  • I tried running your code and it works on my machine with python 2.7.9

    It may be a character encoding issue when you are trying to open the file

    This is my suggestion with the following edits:

    
    import webbrowser
    
    with open("websites.txt", "r+") as sites:
       sites =  sites.readlines()      # readlines returns a list of all the lines in your file, this makes code more concise
                                       # In addition we can use the variable 'sites' to hold the list returned to us by the file object 'sites.readlines()'
    
    
    print sites               # here we send the output of the list to the shell to make sure it contains the right information
    
    for url in sites:
        webbrowser.open_new_tab( url.encode('utf-8') )   # this is here just in-case, to encode characters that the webbrowser module can interpret
                                                                # sometimes special characters like '\' or '/' can cause issues for us unless we encode/decode them or make them raw strings
    
    
    
    

    Hope this helps!