Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Dates and Times in Python (2014) Dates and Times Wikipedia Links

Lexis Hanson
Lexis Hanson
9,128 Points

How to open the Wiki link we generate?

I want to try to make Wikipedia open to the link we generate when trying to run this script. I've tried playing around with the urllib library, but I can't seem to get this to work. Ive tried using url lib.request.urlopen in a couple of different spots, but have no clue whether I'm close or not:

import datetime
import urllib.request

answer_format = '%m/%d'
link_format = '%b_%d'
link = 'https://en.wikipedia.org/wiki/{}'

while True:
    answer = input("What date would you like? Please use the MM/DD format. Enter 'quit' to quit. ")
    if answer.upper() == 'QUIT':
        break

    try:
        date = datetime.datetime.strptime(answer, answer_format)
        output = link.format(date.strftime(link_format))
        urllib.request.urlopen(output)
        print(output)
    except ValueError:
        print("That's not a valid date. Please try again.")

2 Answers

Roman Mayer
Roman Mayer
10,925 Points
    import webbrowser
    webbrowser.open(output, new=2, autoraise=True)

new=2 opens the link in a new tab <br> autoraise=True means your browser will become the active window

Lexis Hanson
Lexis Hanson
9,128 Points

Worked like a charm! Thanks, Roman!

Andy Hughes
Andy Hughes
8,479 Points

Roman Mayer - a great answer which really adds that extra achievement dimension to the wiki code challenge. The only thing to remember for anyone else, is that opening the link doesn't seem to work directly in the treehouse code editor. At least it didn't for me.

However, when I downloaded the script and ran it from a command line, it ran and opened the webpage perfectly. I wish I'd have not spent an hour or so, wondering what I'd done wrong with the script. lol