You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将方法作为参数传递?Selenium POM报错排查

解决Selenium POM中InvalidArgumentException: 'using' must be a string错误

错误根源分析

  1. sel_prd方法无返回值:该方法执行self.driver.find_element(By.LINK_TEXT, psel)后没有返回任何内容,默认返回None。当你把pe.sel_prd(psel)传入find_element时,相当于给方法传了None,不符合find_element要求的参数类型(需传入定位方式+值的元组或合法定位参数),直接触发报错。
  2. 元素定位器作用域错误:类中定义的filter_dd、cart等定位器是__init__内的局部变量,无法通过ProductsPage.filter_dd访问,应该改为实例变量(加self.前缀)。
  3. 不必要的类实例化:selectprod方法里无需重新创建ProductsPage实例,直接用当前实例的self即可调用内部方法。

修复后的代码

from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

from PyFrame.pages.CheckoutPage import CheckoutPage


class ProductsPage:

    def __init__(self, driver):
        self.driver = driver
        # 改为实例变量,让类方法可访问
        self.filter_dd = (By.CLASS_NAME, "product_sort_container")
        self.cart = (By.ID, "add-to-cart-sauce-labs-onesie")
        self.cart_logo= (By.CLASS_NAME , "shopping_cart_link")
    
    def selectprod(self, psel):
        # 直接用self访问实例变量,无需重复实例化类
        dropdown = Select(self.driver.find_element(*self.filter_dd))
        dropdown.select_by_visible_text("Price (low to high)")
        # 调用sel_prd获取元素后直接点击
        self.sel_prd(psel).click()
        self.driver.find_element(*self.cart).click()
        self.driver.find_element(*self.cart_logo).click()
        return CheckoutPage(self.driver)
    
    def sel_prd(self, psel):
        # 返回找到的WebElement对象,供外部调用操作
        return self.driver.find_element(By.LINK_TEXT, psel)

可选写法(返回定位器元组)

如果希望sel_prd只负责提供定位规则,也可以改成返回定位器元组:

def sel_prd(self, psel):
    return (By.LINK_TEXT, psel)

# 对应selectprod里的调用方式
self.driver.find_element(*self.sel_prd(psel)).click()

内容的提问来源于stack exchange,提问作者bot13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:29:52