Python+selenium 多线程启动浏览器

个人博客

通过thredins库实现多线程和通过tomorrow库得threads异步实现

threadins多线程启动浏览器

1.封装一个浏览器启动方法,根据不同参数启动不同浏览器

from time import ctime, sleep
from selenium import webdriver
import threading

def select_browser(browser):
    print("start %s" % browser, ctime())
    try:
        if browser == 'Chrome' or browser == "Ch":
            dr = webdriver.Chrome()
        elif browser == 'Firefox' or browser == 'Ff':
            dr = webdriver.Firefox()
        elif browser == 'Ie' or browser == 'ie':
            dr = webdriver.Ie()
        elif browser == 'phantomjs' or browser == 'PhantomJS':
            dr = webdriver.PhantomJS()
        else:
            print("Not found %s browser,You can use ‘firefox‘, ‘chrome‘, ‘ie‘ or ‘phantomjs‘"% browser)
        return dr
    except Exception as msg:
        print("启动浏览器出现异常:%s" % str(msg))

2.封装一个百度测试用例,根据传参的浏览器名称启动不同浏览器执行测试

def test_baidu(browser_name):
    driver = select_browser(browser_name)
    driver.maximize_window()
    driver.get("https://www.baidu.com")
    driver.find_element_by_id('kw').send_keys('selenium')
    driver.find_element_by_id('su').click()
    sleep(2)
    print(driver.title)
    driver.quit()
    print("end %s" % browser_name, ctime())

3.封装一个threading多线程方法,参数必须传元组

def thread_browser(*args):
    if args:
        threads = []                     # 创建线程列表
        for browser in args:
            t = threading.Thread(target=test_baidu, args=(browser,))    # 创建线程
            threads.append(t)
        for t in threads:
            t.start()                    # 启动线程
        for t in threads:
            t.join()                     # 守护线程
        print("end all time %s"% ctime())
    else:
        print("Please pass at least one browser name")


if __name__ == "__main__":
    thread_browser('Firefox','Chrome')

tomorrow异步启动浏览器

pip安装tomorrow库:python -m pip install tomorrow

#!/usr/bin/python3
# coding=utf-8
from selenium import webdriver
from tomorrow import threads
def test_baidu_01(name):
    driver = select_browser(name)
    driver.maximize_window()
    driver.get("https://www.baidu.com")
    driver.find_element_by_id("kw").send_keys("python")
    driver.find_element_by_id('su').click()
    print(driver.title)
    driver.quit()
    print("quit %s" % name, ctime())

def test_baidu_02(name):
    driver = select_browser(name)
    driver.maximize_window()
    driver.get("https://www.baidu.com")
    driver.find_element_by_link_text("设置").click()
    WebDriverWait(driver, 5, 0.5).until(EC.visibility_of_element_located((By.LINK_TEXT,"搜索设置")),message="搜索设置未出现")
    print(driver.find_element_by_link_text("搜索设置").text)
    driver.find_element_by_link_text("搜索设置").click()
    driver.find_element_by_link_text("保存设置").click()
    driver.quit()

@threads(n=10)            # n为线程数
def all(name):
    test_baidu_01(name)
    test_baidu_02(name)

if __name__ == "__main__":
    browsers = ("Chrome","Firefox")
    for i in browsers:
        all(i)

 

你可能感兴趣的:(selenium)