Jakob Weisblat Jakob Weisblat - 2 months ago 5
Python Question

Download file as string in python

I want to download a file to python as a string. I have tried the following, but it doesn't seem to work. What am I doing wrong, or what else might I do?

from urllib import request

webFile = request.urlopen(url).read()
print(webFile)

Answer

I would recommend that you use urllib2 instead.

import urllib2

url = 'http://www.google.se'
output = urllib2.urlopen(url).read()
print(output)

Alternatively, you could use requests which provides a more human readable syntax. Keep in mind that requests requires that you install additional dependencies, which may increase the complexity of deploying the application, depending on your production enviornment.

 import requests
 output = requests.get(url).text
 print(output)