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

时间:2013-08-15 18:14:39

标签: python python-2.7 urllib2

我正在尝试在Python中打开需要用户名和密码的URL。我的具体实现如下:

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

我收到以下错误吐出到控制台:

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

我正在使用urllib2.urlopen,但错误暗示它无法理解用户凭据。它看到“:”并期望端口号而不是密码和实际地址。我在这里做错了什么想法?

2 个答案:

答案 0 :(得分:9)

使用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")

或使用请求库:

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

答案 1 :(得分:0)

我遇到了需要BasicAuth处理的情况,只有urllib可用(没有urllib2或请求)。 Uku的答案大多有效,但这是我的mods:

interface TestInterface {
    id: number;
    name: string;
}

class Greeter {
    constructor(public greeting: string, public objectField: TestInterface) {
    }

    greet() {
        return "Hello, " + this.greeting + " " + this.objectField.name;
    }
}

let greeter = new Greeter("world", { id: 0, name: 'no name' });

alert(greeter.greet());