[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
We can use such a higher-level interface to download anything with an address on the
Web—files published by FTP sites (using URLs that start with ftp://); web pages and
output of scripts that live on remote servers (using http:// URLs); and even local files
(using file:// URLs). For instance, the script in Example 13-2 does the same as the one
in Example 13-1, but it uses the general urllib.request module to fetch the source
distribution file, instead of the protocol-specific ftplib.

Example 13-2. PP4E\Internet\Ftp\getone-urllib.py
#!/usr/local/bin/python
"""
A Python script to download a file by FTP by its URL string; use higher-level
urllib instead of ftplib to fetch file; urllib supports FTP, HTTP, client-side
HTTPS, and local files, and handles proxies, redirects, cookies, and more;
urllib also allows downloads of html pages, images, text, etc.; see also
Python html/xml parsers for web pages fetched by urllib in Chapter 19;
"""

import os, getpass
from urllib.request import urlopen # socket-based web tools

Figure 13-1. Image file downloaded by FTP and opened locally

858 | Chapter 13: Client-Side Scripting

Do


wnload from Wow! eBook <www.wowebook.com>

Free download pdf