Python urlopen Windows 验证

1 投票
1 回答
7352 浏览
提问于 2025-04-17 00:55

我对Python不太熟悉,下面这段代码是用来打开一个网址并读取响应的。但因为这个网站使用了Windows身份验证,所以我遇到了未授权的错误。有没有人能给我一个代码示例,教我怎么发送用户名和密码呢?

response = urllib.request.urlopen(url, params.encode("ASCII"))
html = response.read()

1 个回答

2

可以试试使用 urllib2python-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())

撰写回答