Playwright TypeError: объект «функция» не поддерживает протокол асинхронного контекстного менеджераPython

Программы на Python
Ответить Пред. темаСлед. тема
Гость
 Playwright TypeError: объект «функция» не поддерживает протокол асинхронного контекстного менеджера

Сообщение Гость »


I use Pyrogram to troll messages from the Telegram channel. Next, I extract the necessary data, which I use Playwright to enter into a form on some site.
Here is an example of the code:

Код: Выделить всё

import re
import logging
from datetime import datetime
from typing import AsyncGenerator

from pyrogram import filters, Client
from pyrogram.types import Message
from playwright.async_api import async_playwright

from keys import API_ID, API_HASH, CANAL_ID_IMEX, LOGIN, PASSWORD, URL

client = Client("my_session", api_id=API_ID, api_hash=API_HASH)

async def get_codes(message: Message) -> AsyncGenerator[str, None]:
"""Example of the message text:
'ZM_GDB4SRHQNK Activate in bonuses.'
"""
promo = [c
for codes in re.findall(
r"(^[a-zA-Z]{2}_[a-zA-Z0-9]{10})",
message.text, flags=re.MULTILINE
)
for c in codes if c]

for code in promo:
yield code

@client.on_message(filters.chat(CANAL_ID_IMEX))
async def message_handler(client: Client, message: Message) -> None:
async for code in get_codes(message):
with async_playwright() as playwright:
browser = await playwright.chromium.launch()
context = await browser.new_context()
page = await context.new_page()
await page.goto(URL)

if __name__ == '__main__':
client.run()
This line

Код: Выделить всё

with async_playwright() as playwright:
leads to the following error:

Код: Выделить всё

2024-03-08 21:16:02,915 - INFO - 256 | 2024-03-08 21:16:03 | ZM_Z263A89F4R | 0:00:00.000022
2024-03-08 21:16:02,915 - ERROR - 'function' object does not support the context manager protocol
Traceback (most recent call last):
File "/home/svbazuev/Zooma/.venv/lib/python3.11/site-packages/pyrogram/dispatcher.py", line 240, in handler_worker
await handler.callback(self.client, *args)
File "/home/svbazuev/Zooma/main.py", line 99, in message_handler
with async_playwright() as playwright:
TypeError: 'function' object does not support the context manager protocol
When I made the changes suggested by ggorlen:

Код: Выделить всё

@client.on_message(filters.chat(CANAL_ID_IMEX))
async def message_handler(client: Client, message: Message) -> None:
async for code in get_codes(message):
if code:
async with async_playwright as p:
browser = await p.chromium.launch()
I got this error:

Код: Выделить всё

2024-03-09 13:02:59,842 - INFO - 274 | 2024-03-09 13:02:59 | ZM_726HBNYRA2 | 0:00:00.000029
2024-03-09 13:02:59,843 - ERROR - 'function' object does not support the asynchronous context manager protocol
Traceback (most recent call last):
File "/home/svbazuev/Zooma/.venv/lib/python3.11/site-packages/pyrogram/dispatcher.py", line 240, in handler_worker
await handler.callback(self.client, *args)
File "/home/svbazuev/Zooma/main.py", line 100, in message_handler
async with async_playwright as p:
TypeError: 'function' object does not support the asynchronous context manager protocol
If I first save the necessary data and upload it separately to the form, I succeed. But I want to execute immediately without saving intermediate results.
I didn't find any explicit instructions in the documentation. I must be missing something. How to solve it?
At first, I used the synchronous implementation of Playwright (Windows OS). I think the problem is related to this. The asynchronous version of Playwright (OS Linux) is already being used in the code example. But I could be wrong...
Resume
Thanks to ggorlen's attentiveness, it became clear that there was no problem.
I was inattentive myself and missed in this line:[/b]

Код: Выделить всё

with async_playwright() as playwright:
And then, looking into ggorlen's "notebook", I missed in this line:[/b]

Код: Выделить всё

async with async_playwright as p:
Be careful!

Источник: https://stackoverflow.com/questions/781 ... ous-contex
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»