如何将方法应用于python中存储在其他文件中的变量?

2024-05-29 02:18:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文件,test_e2e.pyCheckOutPage.pyCheckOutPage.py中有一个方法“getProducts()”,它返回具有特定xpath的所有元素的列表。此列表返回到变量“products”,该变量位于test_e2epage.py中。现在,我正在遍历“产品””列表,并尝试应用一个方法“getProductName()”,该方法存在于CheckOutPage.py,但我无法这样做。代码如下

CheckOutPage.py-

from selenium.webdriver.common.by import By


class CheckOutPage:

    def __init__(self, driver):  #Constructor
        self.driver = driver

    products = (By.XPATH, "//div[@class='card h-100']")
    productName = (By.XPATH, "div/h4/a")

    def getProducts(self):
        return self.driver.find_elements(*CheckOutPage.products)

    def getProductName(self):
        return self.driver.find_element(*CheckOutPage.productName)

测试_e2e.py-

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

# @pytest.mark.usefixtures("setup")
from pageObjects.CheckOutPage import CheckOutPage
from pageObjects.HomePage import HomePage
from utilities.BaseClass import BaseClass


class TestOne(BaseClass):

    def test_e2e(self):

        # Select only Blackberry.
        checkOutPage = CheckOutPage(self.driver)
        products = checkOutPage.getProducts()
        for product in products:
            #productName = product.find_element_by_xpath("div/h4/a").text
            Name = product.checkOutPage.getProductName()
            if Name == "Blackberry":
                product.checkOutPage.selectProduct().click()
                break

测试_e2e.py中for循环的第三行代码失败。 错误为“AttributeError:'webElement'对象没有属性'checkoutPage'”。请帮帮我,伙计们。我被卡住了


Tags: frompytestimportselfbydefdriver
2条回答
Name = product.checkOutPage.getProductName()

循环中的此行尝试从product对象访问属性checkOutPage,该对象是SeleniumWebElement对象,而不是CheckOutPage对象。它没有这样的属性

您正在遍历CheckOutPage返回的web元素,它们不是CheckOutPage返回的方法。这是我应该怎么写的

class TestOne(BaseClass):

    def test_e2e(self):

        # Select only Blackberry.
        checkOutPage = CheckOutPage(self.driver)
        products = checkOutPage.getProducts()
        for product in products:
            #productName = product.find_element_by_xpath("div/h4/a").text
            Name = checkOutPage.getProductName(product)
            if Name == "Blackberry":
                product.checkOutPage.selectProduct().click()
                break

class CheckOutPage:

    def __init__(self, driver):  #Constructor
        self.driver = driver

    products = (By.XPATH, "//div[@class='card h-100']")
    productName = (By.XPATH, "div/h4/a")

    def getProducts(self):
        return self.driver.find_elements(*CheckOutPage.products)

    def getProductName(self, product):
        return self.driver.find_element(*CheckOutPage.productName)

相关问题 更多 >

    热门问题