python urllib包 实现通过http下载文件
为了更通用我们来用HTTPPasswordMgrWithDefaultRealm密码管理器来实现
import urllib.request as urllib2 url = 'http://202.108.1.51' user = 'a' passwd = 'aa' # 登陆连接url psmg = urllib2.HTTPPasswordMgrWithDefaultRealm() psmg.add_password(None,url,user,passwd) hdlr = urllib2.HTTPBasicAuthHandler(psmg) opener = urllib2.build_opener(hdlr) urllib2.install_opener(opener) # 打开url地址文件 f = urllib2.urlopen(url) for i in f: print(i)
with open(os.path.join(os.path.dirname(os.path.abspath("__file__")), 'xxx.txt'), "w+") as f:
for i in r:
a = i.strip().decode() + '\n'
f.write(a)
更多信息见: 参数详解 https://blog.csdn.net/qq_41856814/article/details/99658108
http://www.cnblogs.com/ubunoon/archive/2010/08/25/1807970.html