如何使用python库登录到需要cookie的站点

如何使用python库登录到需要cookie的站点,python,authentication,urllib2,mechanize,python-requests,Python,Authentication,Urllib2,Mechanize,Python Requests,我需要使用python登录到一个站点。这个网站使用cookies。 我试过使用urllib2和请求库和这个 但是这两个函数都返回HTTP错误401:Unauthorized 我应该如何登录网站 编辑 我试着使用机械化,但没有成功 def is_logged_in(html): return auth_data['login'] in html def mechanize_foo(): br = mechanize.Browser() br.open(urls['home

我需要使用python登录到一个站点。这个网站使用cookies。 我试过使用
urllib2
请求
库和这个

但是这两个函数都返回HTTP错误401:Unauthorized

我应该如何登录网站

编辑

我试着使用机械化,但没有成功

def is_logged_in(html):
    return auth_data['login'] in html

def mechanize_foo():
    br = mechanize.Browser()
    br.open(urls['home'])
    br.select_form(nr=0)
    forms = [f for f in br.forms()]
    forms[0].action = urls['login']
    forms[0]['login'] = auth_data['login']
    forms[0]['password'] = auth_data['password']

    response = br.submit()
    print is_logged_in(response.read())

我担心浏览网站不是创建请求的目的。如果要模拟web浏览器,则需要使用名为
mechanize
的库

您当然可以继续这样做,但过一段时间后它会变得非常烦人,因为您需要设置大量的boilterplate代码

这是我所知道的唯一能做到这一点的工具,可能还有其他工具。是指向该站点的链接,您可以在其中学习如何在Python中使用它

编辑
你也可以使用硒。从下载。

我使用firefox+firebug测试登录系统。 主页正在连接到登录。操作两次

它第一次发送
登录
密码
源代码
,并使用一些
令牌
获取JSON数据

第二次发送
登录
密码
源代码
登录登录
(之前已收到)

因此,与该服务器的连接更加复杂

如果您没有经验,最好尝试Selenium或Mechanize(请参阅Games Brainiac答案)。

我知道什么是login.action调用两次。我第一次打电话时出错了。
def is_logged_in(html):
    return auth_data['login'] in html

def mechanize_foo():
    br = mechanize.Browser()
    br.open(urls['home'])
    br.select_form(nr=0)
    forms = [f for f in br.forms()]
    forms[0].action = urls['login']
    forms[0]['login'] = auth_data['login']
    forms[0]['password'] = auth_data['password']

    response = br.submit()
    print is_logged_in(response.read())