Python+Playwright开发AI Agent控制器遇self参数缺失TypeError求助
问题解决:TypeError: Controller.action() missing 1 required positional argument: 'self'
错误根源
你遇到的错误是因为Controller.action是实例方法,但在类定义阶段(装饰get_attr_url方法时),还没有创建Controller的实例,调用Controller.action()时无法自动传入self参数,导致报错。
解决方案
将action装饰器改为类方法或静态方法,这样在类定义阶段就能直接调用装饰器,无需依赖实例。
方案1:将action改为类方法
class Controller: # 用@classmethod将action转为类方法,绑定到类而非实例 @classmethod def action(cls, description): def decorator(func): # 保留原方法的异步逻辑,添加装饰器自定义逻辑(如存储description) async def wrapper(self, *args, **kwargs): return await func(self, *args, **kwargs) # 给包装后的方法附加描述属性,方便后续使用 wrapper.description = description return wrapper return decorator @Controller.action(description='Get attribute and url of the page') async def get_attr_url(self, browser: BrowserSession): page = await browser.get_current_page() current_url = page.url some_attribute = await page.get_by_text('swwg labs').get_attribute('class') print(current_url) return ActionResult(extracted_content = f'The current URL is {current_url} and the attribute is {some_attribute}')
方案2:将action改为静态方法
class Controller: # 用@staticmethod将action转为静态方法,无需类/实例参数 @staticmethod def action(description): def decorator(func): async def wrapper(self, *args, **kwargs): return await func(self, *args, **kwargs) wrapper.description = description return wrapper return decorator @Controller.action(description='Get attribute and url of the page') async def get_attr_url(self, browser: BrowserSession): page = await browser.get_current_page() current_url = page.url some_attribute = await page.get_by_text('swwg labs').get_attribute('class') print(current_url) return ActionResult(extracted_content = f'The current URL is {current_url} and the attribute is {some_attribute}')
额外说明
你之前尝试的写法2存在矛盾:@staticmethod修饰的方法不需要self参数,但你仍在get_attr_url中保留了self,这会导致新的错误。修正装饰器后,不需要给get_attr_url加@staticmethod,因为它是普通的实例方法,需要通过self访问类实例的资源。
内容的提问来源于stack exchange,提问作者user12730187
相关产品推荐
相关产品推荐

