Question

This is a small widget that I am designing that is designed to 'browse' while circumventing proxy settings. I have been told on Code Review that it would be beneficial here, but am struggling to put it in with my program's current logic. Here is the code:

import urllib.request
import webbrowser
import os
import tempfile

location = os.path.dirname(os.path.abspath(__file__))

proxy_handler = urllib.request.ProxyHandler(proxies=None)
opener = urllib.request.build_opener(proxy_handler)


def navigate(query):
    response = opener.open(query)
    html = response.read()
    return html

def parse(data):
    start = str(data)[2:-1]
    lines = start.split('\\n')
    return lines

while True:
    url = input("Path: ")
    raw_data = navigate(url)

    content = parse(raw_data)
    with open('cache.html', 'w') as f:
         f.writelines(content)

    webbrowser.open_new_tab(os.path.join(location, 'cache.html'))

Hopefully someone who has worked with these modules before can help me. The reason that I want to use tempfile is that my program gets raw html, parses it and stores it in a file. This file is overwritten every time a new input comes in, and would ideally be deleted when the program stops running. Also, the file doesn't have to exist when the program initializes so it seems logical from that view also.

Was it helpful?

Solution

Since you are passing the name of the file to webbrowser.open_new_tab(), you should use a NamedTemporaryFile

cache = tempfile.NamedTemporaryFile()
...

cache.seek(0)
cache.writelines(bytes(line, 'UTF-8') for line in content)

cache.seek(0)
webbrowser.open_new_tab('file://' + cache.name)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top