Selenium:循环Web驱动程序(Python)

时间:2020-04-12 19:21:41

标签: python selenium loops selenium-webdriver

我想使用硒运行多个Chrome实例。我尝试循环使用webdriver,但是selenium不断关闭实例。

代码如下:

from selenium import webdriver


user = str(input("Do you want to run this program? "))
amount = 0

if user == "yes":
    amount = int(input("How many instances do you want to run? "))
    for w in range(1, amount+1):
        webdriver.Chrome("path of my driver")
elif user == "no":
    print("Program is closing...")
else:
    print("Invalid input")

奇怪的是,如果我没有循环地编写实例,实例将不会关闭:

from selenium import webdriver


user = str(input("Do you want to run this program? "))

if user == "yes":
    driver1 = webdriver.Chrome("path of driver")
    driver2 = webdriver.Chrome("path of driver")
    driver3 = webdriver.Chrome("path of driver")
    driver4 = webdriver.Chrome("path of driver")
    driver5 = webdriver.Chrome("path of driver")
elif user == "no":
    print("Program is closing...")
else:
    print("Invalid input")

我的问题有解决方案吗?

1 个答案:

答案 0 :(得分:0)

要在没有循环的情况下关闭实例,请执行以下操作。

driver.close()-关闭焦点所在的浏览器窗口 已设置。

driver.quit()–它基本上调用driver.dispose方法,该方法依次 关闭所有浏览器窗口并结束WebDriver会话 优雅地。

无论何时要结束程序,都应使用driver.quit。它将关闭所有打开的浏览器窗口,并终止WebDriver会话。

考虑通过以下方式编写循环示例,这样可以更好地关闭实例。

使用multithreadingmultiprocessingsubprocess模块并行(接近并行)触发任务。

多线程示例

from selenium import webdriver
import threading
import time


def test_logic():
    driver = webdriver.Firefox()
    url = 'https://www.google.co.in'
    driver.get(url)
    # Implement your test logic
    time.sleep(2)
    driver.quit()

N = 5   # Number of browsers to spawn
thread_list = list()

# Start test
for i in range(N):
    t = threading.Thread(name='Test {}'.format(i), target=test_logic)
    t.start()
    time.sleep(1)
    print t.name + ' started!'
    thread_list.append(t)

# Wait for all thre<ads to complete
for thread in thread_list:
    thread.join()

print 'Test completed!'

在这里,生成5个浏览器以一次运行测试用例。为了演示,我没有执行测试逻辑,而是设置了2秒的睡眠时间。该代码将启动5个Firefox浏览器(已通过python 2.7测试),打开google并等待2秒钟后退出。

日志:

C:\Python27\python.exe C:/Users/swadchan/Documents/TestPyCharm/stackoverflow/so49617485.py
Test 0 started!
Test 1 started!
Test 2 started!
Test 3 started!
Test 4 started!
Test completed!

Process finished with exit code 0