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

使用Python Selenium进行Pytest时遭遇参数传递错误求助

问题分析与解决

核心问题

你的代码存在几个不符合Pytest运行逻辑的错误:

  1. 错误手动调用测试方法:Pytest会自动扫描并执行以test_开头的方法,完全不需要自己实例化测试类、手动传参调用
  2. 方法参数不规范:header_test作为类的实例方法,缺少self参数;手动传递self和setup属于画蛇添足,Pytest会自动处理实例化和fixture注入
  3. 冗余导入引发冲突:import self as self完全多余,from setuptools import setup会和你的pytest fixture名setup产生命名冲突

修正后的代码

import time
from pytest import mark
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest

# 定义setup fixture(如果已在conftest.py中定义可忽略)
@pytest.fixture
def setup():
    driver = webdriver.Chrome()  # 替换为你使用的浏览器驱动
    browser = "chrome"
    yield {"driver": driver, "browser": browser}
    driver.quit()

@mark.execute
class First_Tests:

    def test_first(self, setup):
        driver = setup['driver']
        driver.get("https://shuftipro.com/")
        driver.maximize_window()

    def test_header(self, setup):  # 方法名以test_开头,符合Pytest识别规范
        driver = setup['driver']
        # 每个测试独立执行,避免依赖其他测试的状态
        driver.get("https://shuftipro.com/")
        
        # 点击导航栏的Solutions
        solution = driver.find_element(By.ID, "menu-item-72751")
        solution.click()
        if driver.current_url == "https://shuftipro.com/solutions/":
            print("land on solution page.")
        else:
            print("land on wrong page.")

# 移除手动实例化调用的代码,Pytest会自动运行测试

运行方式

在终端执行命令运行测试:

pytest 你的测试文件名.py -v

额外提示

  • Pytest默认仅识别以test_开头的方法,所以将header_test改为test_header更规范
  • 每个测试方法最好独立执行,不要依赖其他测试的运行状态(比如test_header里重新打开首页,避免因测试顺序变化导致失败)
  • 清理冗余导入,避免不必要的命名冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:45:27