Selenium 同时创建多个浏览器对象

2019-04-06  本文已影响0人  假程序员
import threading


class DriverPool(object):
    driver_count = 3  # default count 3
    browser_type = "chrome"
    driver_path = None
    desired_capabilities = None
    lock = threading.Lock()

    @classmethod
    def add_driver(cls, driver):
        """add a driver, it is safe..."""
        if hasattr(cls, "instance"):
            cls.lock.acquire()
            cls.instance[driver.service.port] = (driver, 1)
            cls.driver_count += 1
            cls.lock.release()

    @classmethod
    def free_driver(cls, driver):
        """free a browser driver, it is safe..."""
        if hasattr(cls, "instance"):
            cls.lock.acquire()
            for key, value in cls.instance.items():
                if value[0] is driver:
                    if value[1] is 1:
                        print "This WebDriver has beed freed."
                    else:
                        cls.instance[key] = (value[0], 1)
            cls.lock.release()

    @classmethod
    def get_driver(cls):
        """get a browser driver, it is safe..."""
        if hasattr(cls, "instance"):
            cls.lock.acquire()
            for key, value in cls.instance.items():
                if value[1] is 1:
                    cls.instance[key] = (value[0], 0)
                    print key
                    cls.lock.release()
                    return value[0]  # type:WebDriver
            cls.lock.release()
            return None

    @classmethod
    def release(cls):
        """delete all browser drivers, it is safe..."""
        if hasattr(cls, "instance"):
            cls.lock.acquire()
            for key, value in cls.instance.items():
                value[0].close()
                value[0].quit()
            cls.lock.release()

    @classmethod
    def set_browser(cls, browser_type=browser_type):
        if not hasattr(cls, "instance"):
            cls.lock.acquire()
            browser_type = browser_type.lower()
            if not hasattr(cls, "instance"):
                if browser_type == "chrome":
                    if not cls.driver_path:
                        cls.driver_path = "/Users/apple/Seleniumdriver/chromedriver"
                    from selenium.webdriver.chrome.webdriver import WebDriver
                elif browser_type == "firefox":
                    if not cls.driver_path:
                        cls.driver_path = "geckodriver"
                    from selenium.webdriver.firefox.webdriver import WebDriver
                elif browser_type == "safari":
                    if not cls.driver_path:
                        cls.driver_path = "/usr/bin/safaridriver"
                    from selenium.webdriver.safari.webdriver import WebDriver
                else:
                    if not cls.driver_path:
                        cls.driver_path = "/Users/apple/Seleniumdriver/chromedriver"
                    from selenium.webdriver.chrome.webdriver import WebDriver
                cls.instance = dict()
                for i in range(0, cls.driver_count):
                    driver = WebDriver(executable_path=cls.driver_path,
                                       desired_capabilities=cls.desired_capabilities)
                    cls.instance[driver.service.port] = (driver, 1)
            cls.lock.release()


if __name__ == '__main__':
    from selenium.webdriver.chrome.webdriver import WebDriver

    DriverPool.set_browser()
    browser_driver = DriverPool.get_driver()  # type:WebDriver
    browser_driver.get("http://www.runoob.com")
    DriverPool.free_driver(browser_driver)
    DriverPool.free_driver(browser_driver)
    while True:
        if browser_driver is None:
            break
        else:
            browser_driver.get("https://www.baidu.com")
        browser_driver = DriverPool.get_driver()
    DriverPool.add_driver(WebDriver(executable_path="/Users/apple/Seleniumdriver/chromedriver"))
    DriverPool.release()
/usr/local/bin/python2.7 /Users/apple/PycharmProjects/seleniumHQ/driver_pool.py
59185
This WebDriver has beed freed.
59185
59202
59219

Process finished with exit code 0

以字典类型类属性存储多个driver信息{端口号:(driver,是否可用)}
支持多种浏览器,可自行添加driver,可存储多个类型的浏览器driver。
可无限实例,以类方法加锁来操作类变量保证线程安全。
想要支持更多类型的浏览器,只需扩展set_browser类方法即可。

注意:存放在类中的drivers的close和quit操作统一由release方法实现,所以不能再在其他位置关闭已添加进入drivers的driver。

import unittest
from driver_pool import DriverPool
import time


class Case002(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        DriverPool.driver_count = 1
        DriverPool.set_browser()
        from selenium.webdriver.safari.webdriver import WebDriver
        DriverPool.add_driver(WebDriver())

    @classmethod
    def test_001(cls):
        driver = DriverPool.get_driver()
        driver.get("http://www.runoob.com")
        time.sleep(2)
        # DriverPool.free_driver(driver)

    @classmethod
    def test_002(cls):
        driver = DriverPool.get_driver()
        driver.get("http://www.baidu.com")
        time.sleep(2)

    @classmethod
    def tearDownClass(cls):
        DriverPool.release()
上一篇下一篇

猜你喜欢

热点阅读