Python通过两个标准库thread和threading提供对线程的支持。
我们应避免使用thread模块,原因是它不支持线程守护(即当主线程退出时,所有的子线程不管它们还在工作与否,都会被强行退出)。
from threading import Thread
from selenium import webdriver
from time import sleep, ctime
#测试用例
def test_baidu(host, browser):
print('start: %s' % ctime())
print(host, browser)
#当前运行环境
desired_capabilities = {'browserName': browser}
driver = webdriver.Remote(command_executor = host,
desired_capabilities = desired_capabilities)
driver.get('https://www.baidu.com')
driver.find_element_by_id('kw').send_keys(browser)
sleep(3)
driver.close()
if __name__ == '__main__':
#定义分布式运行环境
env = {'http://localhost:4444/wd/hub': 'chrome',
'http://localhost:5555/wd/hub': 'firefox'}#,
#'http://<remote_ip>:6666/wd/hub': 'internet explorer'}
#定义空线程数组
threads = []
#获取线程数
loops = range(len(env))
#创建线程,并追加入线程数组
for host, browser in env.items():
thread = Thread(target=test_baidu, args=(host, browser))
threads.append(thread)
#启动线程
for i in loops:
threads[i].start()
#守护线程
for i in loops:
threads[i].join()
print('end: %s' % ctime)
网友评论