aiohttp基于表单的身份验证

7
我无法找到与登录页面结合使用的aiohttp工作代码。目标很简单:基于表单的身份验证,需要用户名和密码,我想在后续的异步获取调用中使用cookie。
看起来在版本之间整个会话概念都发生了变化,因此我很好奇如何在最新版本中实现它。我不确定如何一次获取cookie,然后以异步方式使用它。
我真的希望能看到一个完全可行的示例,因为不幸的是,我无法使用我到处找到的片段使其工作。
我猜这可能是开始,但我不确定,我当然也没有看到如何将所有内容连接起来(我还需要aiohttp.TCPConnector吗?) http://aiohttp.readthedocs.org/en/latest/client_reference.html#aiohttp.client.ClientSession 以下是我在Python 2中使用mechanize的非异步版本示例(尽管我自然而然地使用Python 3进行等操作)。
import mechanize
import urllib

class MyClass()
    def __init__(self):
        self.data = {'username' : 'me', 'password' : 'pw'}
        self.login_url = 'http://example.com/login'
        self.login()

    def call(self, url):
        request2 = mechanize.Request(url)
        self.cookie_jar.add_cookie_header(request2)
        response2 = mechanize.urlopen(request2).read()
        return response2    

    def login(self):
        request = mechanize.Request(self.login_url)
        # 'username' and 'password' keys are actually the name of the <input>
        logInfo = urllib.urlencode({'username' : self.data['username'], 
                                    'password' : self.data['password']})
        response = mechanize.urlopen(request, data = logInfo)
        cookie_jar = mechanize.CookieJar()
        cookie_jar.extract_cookies(response, request)
        self.cookie_jar = cookie_jar

mc = MyClass()
mc.call('http://example.com/other_url')
1个回答

3

我刚刚添加了一个客户端基本身份验证的示例代码:client_auth.py

这对您足够了吗?

另外,ClientSession是旧版request+connector概念的替代品。使用会话(Session)可以更自然地保存与会话相关的信息。但旧方法仍然有效。


嘿,非常感谢您的回复!我仍然无法做到这一点;我实际上在哪里提供登录网址?我更新了我的问题,包括之前在Python 2中的代码。 - PascalVKooten
好的。请查看代码片段:https://gist.github.com/asvetlov/218a1d7d05a540d70a21 - Andrew Svetlov
我无法使用print,在我的代码片段中mc.call返回文本。你的 mc.call('http://example.com/other_url') 留下一个生成器。当我尝试打印时,会出现 TypeError: A Future or coroutine is required 错误。它还抱怨有一个未关闭的响应。有任何想法吗? - PascalVKooten
是的,calllogin都是协程。你应该对它们应用yield from - Andrew Svetlov
我已经使用了三个网站来运行最新的代码片段,但它并没有起作用。它总是告诉我我没有登录(使用您的确切代码,唯一的区别是用户名/密码字段和值)。为了辩护自己,我已经使用了urllib、requests、scrapy、mechanize和selenium,而这是第一次它不起作用。 - PascalVKooten
显示剩余5条评论

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