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

如何在Python函数中将Selenium的By类属性设为变量?

解决WebDriverWait动态传入By定位方式的问题

你遇到的AttributeError是因为Selenium的By类中,所有定位方式的属性都是大写命名的(比如By.TAG_NAME、By.ID),并没有小写的tag_name属性,直接调用By.tag_name自然会报错。

要实现动态选择定位方式的需求,有两种简洁的解决方案:

方案1:直接传入By类的属性(推荐)

修改函数参数,让它直接接收By类的属性值,调用时可直接传入By.TAG_NAME、By.ID等定位方式,无需额外转换:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

def webdriver_wait(browser, delay, by_locator, locator_value, success_message, fail_message):
    try:
        element = WebDriverWait(browser, delay).until(
            EC.presence_of_element_located((by_locator, locator_value))
        )
        print(success_message)
        return element
    except TimeoutException:
        print(fail_message)

调用示例:

# 通过TAG_NAME定位
webdriver_wait(driver, 10, By.TAG_NAME, "div", "成功找到div元素", "超时未找到div元素")

# 通过ID定位
webdriver_wait(driver, 10, By.ID, "username", "成功找到用户名输入框", "超时未找到用户名输入框")

# 通过XPATH定位
webdriver_wait(driver, 10, By.XPATH, "//button[@type='submit']", "成功找到提交按钮", "超时未找到提交按钮")

这种方式直观且能避免字符串转换带来的错误,是优先推荐的实现方式。

方案2:传入字符串形式的定位类型(需转换)

如果需要通过字符串(比如"tag_name"、"id")指定定位方式,可以用getattr()函数动态获取By类的属性,同时统一转换为大写匹配By类的命名规则:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

def webdriver_wait(browser, delay, locator_type, locator_value, success_message, fail_message):
    try:
        # 将传入的定位类型转为大写,匹配By类的属性名
        by_locator = getattr(By, locator_type.upper())
        element = WebDriverWait(browser, delay).until(
            EC.presence_of_element_located((by_locator, locator_value))
        )
        print(success_message)
        return element
    except TimeoutException:
        print(fail_message)
    except AttributeError:
        print(f"无效的定位类型:{locator_type},请使用TAG_NAME/ID/XPATH/CSS_SELECTOR等合法值")

调用示例:

webdriver_wait(driver, 10, "tag_name", "div", "成功找到div元素", "超时未找到div元素")
webdriver_wait(driver, 10, "css_selector", ".submit-btn", "成功找到提交按钮", "超时未找到提交按钮")

注意事项

  • 确保导入所有必要的模块:WebDriverWait、expected_conditions、By、TimeoutException
  • 函数参数名可根据习惯调整(比如把locator_value换回原来的tag,只要调用时保持一致即可)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:20:35