Python Network Programming 简明教程

Python - HTTP Data Download

我们可以使用处理 ftp 或文件传输协议的 Python 模块从服务器下载数据。我们还可以读取数据,稍后再将其保存到本地系统。

We can download data from a serer using python’s module which handle ftp or File Transfer Protocol. We can also read the data and later save it to the local system.

我们需要安装模块 ftplib 才能实现此目的。

We need to install the module ftplib to acheive this.

pip install ftplib

Fetching the Files

我们可以使用 getfile 方法获取特定文件。此方法将文件的副本从远程系统移动到建立 ftp 连接的本地系统。

We can fetch a specific file by using the getfile method. This method moves a copy of the file from the remote system to the local system from where the ftp connection was initiated.

import ftplib
import sys

def getFile(ftp, filename):
    try:
        ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write)
    except:
        print "Error"


ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")

ftp.cwd('/pub/')          change directory to /pub/
getFile(ftp,'README.nluug')

ftp.quit()

当我们运行上面的程序时,我们发现文件 README.nlug 存在于发起连接的本地系统中。

When we run the above program, we find the file README.nlug to be present in the local system from where the connection was initiated.

Reading the Data

在以下示例中,我们使用模块 urllib2 读取必要部分的数据,我们可将该部分数据复制并保存到本地系统。

In the below example we use the module urllib2 to read the required portion of the data which we can copy and save it to local system.

当我们运行以上程序时,我们得到以下输出:

When we run the above program, we get the following output −

import urllib2
response = urllib2.urlopen('http://www.tutorialspoint.com/python')
html = response.read(200)
print html

当我们运行以上程序时,我们得到以下输出:

When we run the above program, we get the following output −

<!DOCTYPE html>
<!--[if IE 8]><html class="ie ie8"> <![endif]-->
<!--[if IE 9]><html class="ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->  <html> <!--<![endif]-->
<head>
<!-- Basic -->
<meta charset="ut