我对python没有经验,并使用下面的代码打开一个url并阅读响应。我收到了未经授权的错误,因为该站点使用Windows身份验证。有人可以提供有关如何发送用户名和密码的代码示例吗?
response = urllib.request.urlopen(url, params.encode("ASCII"))
html = response.read()
答案 0 :(得分:2)
尝试使用urllib2和python-ntlm一些示例代码:
import urllib2
from ntlm import HTTPNtlmAuthHandler
user = 'DOMAIN\User'
password = "Password"
url = "http://ntlmprotectedserver/securedfile.html"
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, password)
# create the NTLM authentication handler
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
# create and install the opener
opener = urllib2.build_opener(auth_NTLM)
urllib2.install_opener(opener)
# retrieve the result
response = urllib2.urlopen(url)
print(response.read())