繁体   English   中英

如何同时运行两个selenium python程序

[英]How to run two selenium python program at same time

我想同时运行代码两次以节省时间。 我是一个初学者,我正在对此进行一些研究并获得多线程这个词并听说过 pytest 库,但我不知道该怎么做,甚至我找不到示例代码。 请帮我! 我等着你的回答

import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from shutil import which
import time
import pandas as pd
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
Links = []
chrome_path = which('chromedriver')
driver = webdriver.Chrome(executable_path=chrome_path)
driver.maximize_window()

driver.get('https://www.google.com')

text = driver.find_element_by_xpath('//input[@class="gLFyf gsfi"]')
text.send_keys('Hello')

driver.find_element_by_xpath('//div[@class="FPdoLc tfB0Bf"]//input[1]').click()
time.sleep(3)

driver.close()

我想同时跑两次? 任何人帮助我

将整个 selenium 代码重构为一个接受 webdriver 实例作为输入的类/方法(这不是强制性的,只是利益分离)。

然后你运行那个方法作为你想要的线程数。

这是一个基于您的代码的示例,还添加了从每个线程获取结果的代码。

import time

import concurrent.futures
from selenium import webdriver


def task(driver):
    driver.get('https://www.google.com')
    text = driver.find_element_by_xpath('//input[@class="gLFyf gsfi"]')
    text.send_keys('Hello')
    driver.find_element_by_xpath('//div[@class="FPdoLc tfB0Bf"]//input[1]').click()
    time.sleep(3)
    driver.close()


if __name__ == '__main__':
    futures = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        for i in range(3):
            driver = webdriver.Chrome(executable_path="./chromedriver")
            driver.maximize_window()
            futures.append(executor.submit(task, driver))
    for future in futures:
        print(future.result())

您始终可以使用“Jupyter Notebooks”,然后您可以使用新名称另存为脚本并同时运行它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM