Python HTTP 数据下载
我们可以使用处理 ftp 或文件传输协议的 python 模块从 serer 下载数据。我们还可以读取数据,然后将其保存到本地系统。
我们需要安装模块 ftplib 实现这一目标。
pip install ftplib
获取文件
我们可以使用 getfile 方法。此方法将文件的副本从远程系统移动到 启动 ftp 连接的本地系统。
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 存在于启动连接的本地系统中。
读取数据
在下面的示例中,我们使用模块 urllib2 读取数据的所需部分,我们可以将其复制并保存到本地系统。
当我们运行上面的程序时,我们得到如下输出:
import urllib2 response = urllib2.urlopen('http:// www.newbiego.com/python') html = response.read(200) print html
当我们运行上面的程序时,我们得到如下输出:
<!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