8.1. Simple Web Tasks

8.1.1. Downloading Data from the Web

You can download any HTML page, image, sound or any other file from the web in one line of code.

Example 8.1. Web downloader
import urllib
page = urllib.urlopen("http://www.python.org").read()
print page

The script prints out the HTML contents of the Python home page. The module urllib contains functions related to web communication. Whenever you need to download something from the web, you can use the urllib.urlopen() function, which returns the file contents to your program so that they can be further processed.

On the other hand, if you want to download a file from the web and save it locally, you can use the urllib.urlretrieve() function to save the file directly to a given file name, as shown in Example 67. If the URL contains unusual characters, such as spaces, you can use the urllib.quote() function to encode them properly.

This example downloads the Python logo from the Python website and shows it using the phone's default image viewer.

Example 8.2. Webfile viewer
import urllib, appuifw, e32

URL = "http://www.python.org/images/python-logo.gif"

dest_file = u"E:\\Images\\python-logo.gif"
urllib.urlretrieve(URL, dest_file)
lock = e32.Ao_lock()
viewer = appuifw.Content_handler(lock.signal)
viewer.open(dest_file)
lock.wait()

This example uses the function urllib.urlretrieve() to download data from a URL to a local file. When the data has been saved, the default viewer associated with the URL's file type is used to ...

Get Mobile Python: Rapid Prototyping of Applications on the Mobile Platform now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.