Python httplib.InvalidURL: 非数字端口失败。

4

我正在尝试在Python中打开一个需要用户名和密码的URL。我的具体实现看起来像这样:

http://char_user:char_pwd@casfcddb.example.com/......

我在控制台看到以下错误:

httplib.InvalidURL: nonnumeric port: 'char_pwd@casfcddb.example.com'

我正在使用urllib2.urlopen,但错误提示表明它无法理解用户凭据。它看到“:”并期望一个端口号而不是密码和实际地址。你有什么想法吗?
2个回答

10

使用BasicAuthHandler提供密码:

import urllib2

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, "http://casfcddb.xxx.com", "char_user", "char_pwd")
auth_handler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
urllib2.urlopen("http://casfcddb.xxx.com")

或者使用requests库:

import requests
requests.get("http://casfcddb.xxx.com", auth=('char_user', 'char_pwd'))

使用第一个代码片段会出现以下错误: TypeError: 期望 BaseHandler 实例,但得到了 <type 'instance'>。 - milnuts
我仍然在收到以下信息:urllib2.HTTPError: HTTP错误401:未经授权。让我跟创建该页面的人确认一下,以确认他没有在他那边弄错了什么。 - milnuts
作为一个可靠性检查,我在已知的良好页面上运行了这个Python程序,结果非常正常。因此,这证实了当前问题在于新页面的访问权限,我会和设计师进行沟通。感谢你的帮助。 - milnuts
另一方必须正确实现协议,否则可能无法正常工作。让其在您的一侧正常工作的更简单的方法是设置一个标题 `Authorization:base64encodedstringhere',其中base64encodedstring是字符串b64encode(username:password)。 - Uku Loskit

0

我遇到了一个情况,需要进行BasicAuth处理,但只有urllib可用(没有urllib2或requests)。Uku的答案大部分都有效,但这是我的修改:

import urllib.request
url = 'https://your/url.xxx'
username = 'username'
password = 'password'
passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
auth_handler = urllib.request.HTTPBasicAuthHandler(passman)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
resp = urllib.request.urlopen(url)
data = resp.read()

我尝试了,但它响应“'Request'对象不可迭代”。 - Miguel Herreros Cejas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接