Python: 类型错误:'协程' 对象不支持下标操作。

11

当尝试从anticaptcha函数中访问JSON对象的下标时,该函数中一直出现异常,但所有其他函数似乎都工作正常。

'email':email, 'username': username, 'password': passwd, 'invite': None, 'captcha_key': await anticaptcha.solve(session, 'register')['solution']['gRecaptchaResponse']
TypeError: 'coroutine' object is not subscriptable
async def register(session, username, email, passwd):
    """
    sends a request to create an account
    """
    async with session.post('http://randomsite.com',
                            headers={
                                'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0'
                            },
                            json={
                                'email':email, 'username': username, 'password': passwd, 'invite': None, 'captcha_key': await anticaptcha.solve(session, 'register')['solution']['gRecaptchaResponse']
                            }) as response:
            return await response.json()

来自于 anticaptcha 文件的函数

async def task_result(session, task_id):
    """
    sends a request to return a specified captcha task result
    """
    while True:
        async with session.post('https://api.anti-captcha.com/getTaskResult',
                                json={
                                    "clientKey": ANTICAPTCHA_KEY,
                                    "taskId": task_id
                                }) as response:
            result = await response.json()
            if result['errorId'] > 0:
                print(colored('Anti-captcha error: ' + result['statusCode']), 'red')
            else:
                if result['status'] == 'ready':
                    return await result

async def solve(session, url):
   await get_balance(session)
   task_id = await create_task(session, url)['taskId']
   return await task_result(session, task_id)
2个回答

23
await anticaptcha.solve(session, 'register')['solution']['gRecaptchaResponse']
意思
await (anticaptcha.solve(session, 'register')['solution']['gRecaptchaResponse'])

但是您希望

(await anticaptcha.solve(session, 'register'))['solution']['gRecaptchaResponse']

如果其他类似的事情,task_id = await create_task(session, url)['taskId'],正在工作,那么它可能不会返回一个future对象,你只需要设置

task = create_task(session, url)['taskId']

没有使用 await


基本上,可等待对象返回一个(嵌套的)字典,一旦等待完成,您就可以从字典中检索值:(await function()) -> dict - D.L

-2

除了已接受的方法外,还有一种方法稍微长了一行,但增加了一些清晰度。

x = await anticaptcha.solve(session, 'register')    # first do the await
x = x['solution']['gRecaptchaResponse']             # then get the dict values

上面的内容清楚地展示了发生了什么。当我第一次遇到相同情况时,我发现上述内容有助于澄清问题(而不是在代码中添加注释)。


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