Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

/prog/ Challenge

Name: Anonymous 2010-07-29 0:55

Write a web browser and post inside it on /prog/

Name: Anonymous 2010-07-29 15:08

>>1
Done.  Elapsed time: ~20 minutes.  Is a functional web browser.  Does not support HTML.


#!/usr/bin/env python3
import urllib.request, urllib.parse, readline
def browse():
    last_url = ''
    while True:
        if last_url: print("Location:", last_url)
        try:
            url = input("Enter URL: ")
        except (KeyboardInterrupt, EOFError):
            print()
            return
        if last_url: url = urllib.parse.urljoin(last_url, url)
        try:
            req = urllib.request.urlopen(url)
            if req.headers.get_content_maintype() == 'text':
                text = req.readall()
                try:
                    text = text.decode(req.headers.get_content_charset() or 'utf-8', 'replace')
                except LookupError:
                    text = text.decode('utf-8', 'replace')
                print(text)
                last_url = url
            else:
                print("Content type:", req.headers.get_content_type())
                try:
                    loc = input("Save as: ")
                except (KeyboardInterrupt, EOFError):
                    print()
                    print("Canceled")
                    continue
                n = 0
                with open(loc, 'wb') as file:
                    while True:
                        data = req.read(4096)
                        if not data:
                            break
                        n += len(data)
                        file.write(data)
                        print("\rDownloaded:", n, "bytes", end='')
                print()
        except urllib.error.URLError as ex:
            print(ex)
browse()

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List