class ChromeInit:
@classmethod
def init(cls):
options = webdriver.ChromeOptions()
options.add_argument('--disable-infobars') # 禁用浏览器正在被自动化程序控制的提示
options.add_argument('--start-maximized')
# 针对禁止加载图片的操作
# prefs = {"profile.managed_default_content_settings.images": 2}
# options.add_experimental_option("prefs", prefs)
# options.add_argument('--disable-infobars') # 禁止策略化
# options.add_argument('--no-sandbox')
# options.add_argument('--incognito') # 隐身模式(无痕模式)
# options.add_argument('--disable-javascript')
# options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片, 提升速度
# options.add_argument('--proxy-server=http://ip:port') # 尽量选择静态IP,提升稳定性
# options.add_argument('--headless') # 浏览器不提供可视化页面. linux下必须
return webdriver.Chrome("D:/chromedriver.exe", chrome_options=options)
# 同一线程每次获取driver都会先去threadlocal查看,如果存在则直接使用,不存在则新建,所有同一个线程全程使用一个driver。因为初始化一个driver很耗时,这样可以提高效率
class DriverDataSource:
thread_local = threading.local()
@classmethod
def get_driver(cls):
thread_name = threading.current_thread().getName()
driver = getattr(cls.thread_local, thread_name, None)
if driver is None:
setattr(cls.thread_local, thread_name, ChromeInit.init())
return getattr(cls.thread_local, thread_name, None)
@classmethod
def delete_driver(cls):
thread_name = threading.current_thread().getName()
driver = getattr(cls.thread_local, thread_name, None)
if driver:
delattr(cls.thread_local, thread_name)
driver.quit()
@classmethod
def new_driver(cls):
cls.delete_driver()
driver = ChromeInit.init()
thread_name = threading.current_thread().getName()
setattr(cls.thread_local, thread_name, driver)
return driver
# 该种方式的好处:在testcase里看不到driver,同一线程绑定一个driver,刚好配合多线程使用
class WaitElementBy:
WAIT_TIME = 10
@classmethod
def class_name(cls, locator):
e = WebDriverWait(DriverDataSource.get_driver(), cls.WAIT_TIME).until(
EC.presence_of_element_located((By.CLASS_NAME, locator))
)
return e
@classmethod
def id(cls, locator):
e = WebDriverWait(DriverDataSource.get_driver(), cls.WAIT_TIME).until(
EC.presence_of_element_located((By.ID, locator))
)
return e
@classmethod
def xpath(cls, locator):
e = WebDriverWait(DriverDataSource.get_driver(), cls.WAIT_TIME).until(
EC.presence_of_element_located((By.XPATH, locator))
)
return e
@classmethod
def tag_name(cls, locator):
e = WebDriverWait(DriverDataSource.get_driver(), cls.WAIT_TIME).until(
EC.presence_of_element_located((By.TAG_NAME, locator))
)
return e