WebDriver 问题 - AttributeError:“NoneType”对象没有属性

问题描述 投票:0回答:1
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

driver = None


def pytest_addoption(parser):
    parser.addoption(
        "--browser_name", action="store", default="chrome"
    )


@pytest.fixture(scope="class", autouse=True)
def setup(request):
    global driver
    # chrome_options = webdriver.ChromeOptions()
    # chrome_options.add_experimental_option("detach", True)
    service_obj = Service("/Users/ibrahim/SeleniumProjects/BrowserDrivers/chromedriver")
    # Chrome driver service
    browser_name = request.config.getoption("browser_name")

    if browser_name == "chrome":
        driver = webdriver.Chrome(service=service_obj)  # Initialize chrome driver class
    elif browser_name == "safari":
        driver = webdriver.Safari()
    elif browser_name == "firefox":
        driver = webdriver.Firefox()
    driver.get("https://rahulshettyacademy.com/angularpractice/")
    driver.implicitly_wait(5)
    driver.maximize_window()
    request.cls.driver = driver

    yield 
    driver.close()


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
        Extends the PyTest Plugin to take and embed screenshot in html report, whenever test fails.
        :param item:
        """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_") + ".png"
            _capture_screenshot(file_name)
            if file_name:
                html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % file_name
                extra.append(pytest_html.extras.html(html))
        report.extra = extra


def _capture_screenshot(name):
    driver.get_screenshot_as_file(name)

这是我的conftest 文件中的代码。我将驱动程序初始化为无,并在 setup() 和安装装置下全局调用。我有自定义报告代码(当测试失败时它会捕获屏幕截图)。我正在使用驱动程序对象来捕获屏幕截图,但由于以下原因我无法运行测试:

AttributeError: 'NoneType' object has no attribute 'get_screenshot_as_file' error.

python selenium-webdriver pytest
1个回答
1
投票

根据您的评论,您可以按照以下步骤操作:

1- 验证您是否拥有最新版本;

硒版本:4.22.0

Chrome版本:126.0.6478.126/127

2-(可选)考虑删除report.when == 'setup',除非您打算将这部分代码执行两次,因为report.when == 'call'似乎更适合您的情况

3-删除“service_obj”

4-(可选)添加对意外浏览器名称的错误处理

5-(可选)更新已弃用的“report.extra”和“@pytest.mark.hookwrapper”的“pytest_runtest_makereport”函数。

下面的代码涵盖第 2、3、4 和 5 项,预计可以工作。

(我使用Python版本3.12.4,pytest版本8.2.2和pytest-html版本4.1.1)

import pytest
from selenium import webdriver


driver = None


def pytest_addoption(parser):
    parser.addoption(
        "--browser_name", action="store", default="chrome"
    )


@pytest.fixture(scope="class", autouse=True)
def setup(request):
    global driver
    browser_name = request.config.getoption("browser_name")

    if browser_name == "chrome":
        driver = webdriver.Chrome()
    elif browser_name == "safari":
        driver = webdriver.Safari()
    elif browser_name == "firefox":
        driver = webdriver.Firefox()
    else:
        raise pytest.UsageError("--browser_name should be chrome, safari, or firefox")

    driver.get("https://rahulshettyacademy.com/angularpractice/")
    driver.implicitly_wait(5)
    driver.maximize_window()
    request.cls.driver = driver

    yield 
    
    driver.close()


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
    """
    Extends the PyTest Plugin to take and embed screenshot in html report, whenever test fails.
    :param item:
    """
   
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    if report.when == 'call':
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_") + ".png"
            _capture_screenshot(file_name)
            if file_name:
                html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % file_name
                extra.append(pytest_html.extras.html(html))
        report.extras = extra


def _capture_screenshot(name):
    driver.get_screenshot_as_file(name)
 
© www.soinside.com 2019 - 2024. All rights reserved.