我有一个Python 2.6脚本,可以从Web服务器下载文件。我希望此脚本传递用户名和密码(在获取文件之前进行身份验证),然后将它们作为url的一部分传递,如下所示:
import urllib2
response = urllib2.urlopen("http://'user1':'password'@server_name/file")
但是,在这种情况下,我收到语法错误。这是正确的方法吗?我对Python和一般的编码非常陌生。有人可以帮我吗?谢谢!
我想您正在尝试通过基本身份验证。在这种情况下,可以这样处理:
import urllib2
username = 'user1'
password = '123456'
#This should be the base url you wanted to access.
baseurl = 'http://server_name.com'
#Create a password manager
manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, baseurl, username, password)
#Create an authentication handler using the password manager
auth = urllib2.HTTPBasicAuthHandler(manager)
#Create an opener that will replace the default urlopen method on further calls
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener)
#Here you should access the full url you wanted to open
response = urllib2.urlopen(baseurl + "/file")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句