【问题标题】:Accessing a web page with basic auth on python在 python 上使用基本身份验证访问网页
【发布时间】:2014-04-07 10:25:44
【问题描述】:

我正在尝试使用 mechanize 连接网页,但遇到 http 401 错误。

这是我的代码;

import base64, mechanize

url = "http://www.dogus.edu.tr/dusor/FrmMain.aspx"
user = "user"
pwd = "pwd"

br = mechanize.Browser()
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

br.add_password(url, user, pwd)
#br.addheaders.append(('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (user, pwd))))
print br.open(url).read()

add_passwordaddheaders 都不起作用。是因为我从未指定领域吗?如何获取该网页使用的领域?我使用的用户名和密码是正确的,因为我可以使用带有这些凭据的 chrome 登录。

【问题讨论】:

  • 我能够按原样运行您的代码以访问需要 HTTP 基本身份验证的页面。
  • 是的,但该代码不适用于该页面。可能是领域的问题,如果是其他问题,我还缺少什么?

标签: python mechanize basic-authentication


【解决方案1】:

您用作示例页面的站点需要NTLM 身份验证。您可以通过查看返回的 HEADER 字段来看到这一点。例如curl -I http://www.dogus.edu.tr/dusor/FrmMain.aspx 返回:

HTTP/1.1 401 Unauthorized
Content-Length: 1293
Content-Type: text/html
Server: Microsoft-IIS/7.0
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
Date: Mon, 07 Apr 2014 21:24:09 GMT

WWW-Authenticate: NTLM 行表示使用哪种身份验证方法。我想这个问题的答案Use python mechanize to log into pages with NTLM authentication会对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-10
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多