Python3:使用用户名/密码

时间:2016-01-30 07:56:07

标签: python http passwords request username

我正在尝试从Yahoo幻想足球页面下载DOM。该数据需要雅虎用户。我正在寻找python库,我可以将我的用户/传递添加到请求中。

urllib有HTTPBasicAuthHandler,需要HTTPPasswordMgr Objects

add_password字段表示我错过了一个参数,当我尝试将它传递给它想要的4时。我不知道该为这个领域投入什么。我是Python的新手。

我发现Requests看起来很有前途,但是当我安装它时,它会抛出一个错误,我无法正确导入它:\

我希望在Python中更容易做到这一点!

import urllib.request
try:
    url = "http://football.fantasysports.yahoo.com/" 
    username = "un"
    password = "pw"

    pwObj = urllib.request.HTTPPasswordMgr.add_password("http://yahoo.com",url, username, password)
    request = urllib.request.HTTPBasicAuthHandler(pwObj)

    result = urllib.request.urlopen(request)

    print(result.read())


except Exception as e:
    print(str(e))
# Error: add_password() missing 1 required positional argument: 'passwd'

理想的解决方案是让某人从需要凭据的页面下载雅虎DOM数据:)

1 个答案:

答案 0 :(得分:1)

像这样:

import urllib.request
try:
    url = "http://football.fantasysports.yahoo.com/" 
    username = "_username"
    password = "_password"

    password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
    password_mgr.add_password(None, url, username, password)
    handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
    opener = urllib.request.build_opener(handler)
    opener.open("http://football.fantasysports.yahoo.com/f1/leaderboard")
    urllib.request.install_opener(opener)

    result = urllib.request.urlopen(url)

    print(result.read())


except Exception as e:
    print(str(e))

但是,如何运行java事件?

相关问题