我无法找到与登录页面结合使用的
看起来在版本之间整个会话概念都发生了变化,因此我很好奇如何在最新版本中实现它。我不确定如何一次获取cookie,然后以异步方式使用它。
我真的希望能看到一个完全可行的示例,因为不幸的是,我无法使用我到处找到的片段使其工作。
我猜这可能是开始,但我不确定,我当然也没有看到如何将所有内容连接起来(我还需要
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')
mc.call('http://example.com/other_url')
留下一个生成器。当我尝试打印时,会出现TypeError: A Future or coroutine is required
错误。它还抱怨有一个未关闭的响应。有任何想法吗? - PascalVKootencall
和login
都是协程。你应该对它们应用yield from
。 - Andrew Svetlov