如何同时运行多个Web驱动程序python程序



我有 4 个 Python 脚本(3 个 Web 驱动程序和一个主脚本(。我想在运行 mainscript.py 时同时打开这 3 个 Web 驱动程序。我使用了多处理,但你可以使用任何你想要的东西。

现在它打开bot_1.py,然后打开bot_2.py,然后打开bot_3.py

bot_1.py

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\UsersAndreiDownloadschromedriver_win32chromedriver.exe")
links=['https://ro.wikipedia.org/wiki/Emil_Constantinescu','https://ro.wikipedia.org/wiki/Traian_B%C4%83sescu','https://ro.wikipedia.org/wiki/Napoleon_I']
for i in range(len(links)):
    driver.get(links[i])

bot_2.py

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\UsersAndreiDownloadschromedriver_win32chromedriver.exe")
links=['https://ro.wikipedia.org/wiki/Abraham_Lincoln','https://ro.wikipedia.org/wiki/Winston_Churchill','https://ro.wikipedia.org/wiki/Mihail_Gorbaciov']
for i in range(len(links)):
    driver.get(links[i])

bot_3.py

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\UsersAndreiDownloadschromedriver_win32chromedriver.exe")
links = ['https://ro.wikipedia.org/wiki/Gabriela_Firea', 'https://ro.wikipedia.org/wiki/Ion_Iliescu',
         'https://ro.wikipedia.org/wiki/Mihai_Eminescu']
for i in range(len(links)):
    driver.get(links[i])

mainscript.py

import bot_1, bot_2, bot_3
import multiprocessing
for bot in ('bot_1', 'bot_2','bot_3'):
    p = multiprocessing.Process(target=lambda: __import__(bot))
    p.start()
带有

xdist扩展的PyTest是一个选项:https://docs.pytest.org/en/3.0.0/xdist.html

pip install pytest
pip install pytest-xdist

然后运行 pytest -n NUM ,其中NUM是要运行的进程数(或在本例中为 Web 驱动程序实例(。我现在不记得了,但我认为上面的命令运行您当前文件夹中的所有.py文件。

您还可以使用"行为 + 行为并行"。

https://github.com/hugeinc/behave-parallel

这是并行运行的。但这也许并不明显,因为对我来说,这是两个重叠的窗口。所以,我添加了时间.睡眠

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from  multiprocessing import Process
#import time
def run(urls):
#    print ("run", urls)
    options = Options()
    options.add_argument('--no-sandbox')
    options.add_argument('--no-default-browser-check')
    options.add_argument('--disable-gpu')
    options.add_argument('--disable-extensions')
    options.add_argument('--disable-default-apps')
    options.binary_location = '/opt/chrome-linux.63.0.3239.b.508580/chrome'
    driver = webdriver.Chrome(
                executable_path='/opt/chromedriver/chromedriver',
                options=options,
                )
    for url in urls:
#        time.sleep(5)
        driver.get(url)
#        print driver.title
    driver.quit()
allurls = [
        ['http://ya.ru', 'http://google.ru'],
        ['https://ro.wikipedia.org/wiki/Emil_Constantinescu',
            'https://ro.wikipedia.org/wiki/Traian_B%C4%83sescu'],
        ]
processes = []
for urls in allurls:
    p = Process(target=run, args=(urls,))
    processes.append(p)
    p.start()
for p in processes:
    p.join()

相关内容

  • 没有找到相关文章

最新更新