use*_*537 5 python urllib2 python-2.6
我有一个Python 2.6脚本,可以从Web服务器下载文件.我希望这个脚本传递用户名和密码(在获取文件之前进行身份验证),我将它们作为URL的一部分传递,如下所示:
import urllib2
response = urllib2.urlopen("http://'user1':'password'@server_name/file")
Run Code Online (Sandbox Code Playgroud)
但是,在这种情况下,我收到语法错误.这是正确的方法吗?我对Python和编码很新.有人可以帮帮我吗?谢谢!
wil*_*lnx 12
如果您可以使用请求库,那就太简单了.我强烈建议尽可能使用它:
import requests
url = 'http://somewebsite.org'
user, password = 'bob', 'I love cats'
resp = requests.get(url, auth=(user, password))
Run Code Online (Sandbox Code Playgroud)
我想您正在尝试通过基本身份验证。在这种情况下,您可以这样处理:
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")
Run Code Online (Sandbox Code Playgroud)