【问题标题】:What is the best way to create webdriver instance in selenium Python with Pytest使用 Pytest 在 selenium Python 中创建 webdriver 实例的最佳方法是什么
【发布时间】:2021-08-05 08:44:58
【问题描述】:

我是 python 新手,我想创建 web 驱动程序实例 我找到了两种方法

首先:创建夹具并在基类中使用夹具,并在需要的地方继承该基类。但这不起作用。这里的设置夹具在 conftest.py 文件中是正确的

基类:

@pytest.mark.usefixtures("setup")
class BaseTest:

    @staticmethod
    def go_to_url(url):
        print(".............Launching Application URL : " + url)
        # Driver.Instance.get(url)
        Driver.Instance.get(url)

    @staticmethod
    def maximize_window_size():
        print("..............Maximizing browser window..............")
        Driver.Instance.maximize_window()

页面对象:

Class page_object_class1:
value_xpath="//div[@id='excr']"
SeleniumUIAction.IsDisplayed(self.value_xpath)

Action 类:这会产生错误,例如 SeleniumUIAction 没有“驱动程序”属性。在这里,我们继承了 BaseTest 类,所以我认为它应该是自动来自 BaseTest 类。原因我能够启动和最大化浏览器,所以直到 BaseTest 类我得到驱动程序的引用,但是当我在页面对象类中引用该驱动程序时出现错误。任何建议将不胜感激

class SeleniumUIAction(BaseTest):

    def click_element(self,value_xpath):
        self.driver.find_element_by_xpath(value_xpath).click()
        

第二:创建没有类的Driver.py,如下所示,并在需要的地方使用Driver.Instance。我没有发现第二种方法的问题,但不知道这是否支持并行执行

from selenium import webdriver

Instance = None

def Initialize():
    global Instance
    Instance = webdriver.Chrome("C://hromedriver.exe")
    Instance.implicitly_wait(5)
    return Instance

【问题讨论】:

    标签: python python-3.x selenium pytest


    【解决方案1】:

    这是我使用的,对我来说效果很好。

    @pytest.fixture()
        def test_setup(self):
            #initiating chrome driver
            global driver
            chrome_options=Options()
            chrome_options.add_argument('--start-maximized')
            driver = webdriver.Chrome(executable_path=r"{{Your driver path}}",
                                      chrome_options=chrome_options)
    
        def test_01(self, test_setup):
                driver.get(//page_url//)
                actual_title=driver.title
    

    【讨论】:

    • 我正在使用扩展 BaseClass 的页面对象中的驱动程序。在同一个班级,这对我来说也很好
    猜你喜欢
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多