简体   繁体   English

如何在 c# 中的 selenium 中打开多个浏览器实例?

[英]How can I open multiple browser instances in selenium in c#?

I want my program to open multiple browser instances at once and perform actions.我希望我的程序一次打开多个浏览器实例并执行操作。 But I ran into a problem, which is that all actions are performed in turn.但是我遇到了一个问题,就是所有的动作都是轮流执行的。 I have a list of proxy servers and data from them, how do I make several browser instances open at once and they start working?我有一个代理服务器列表和来自它们的数据,如何让多个浏览器实例同时打开并开始工作?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
using System.Threading;
using OpenQA.Selenium.Chrome.ChromeDriverExtensions;
using System.IO;

namespace LoveStackOverflow
{
    public partial class Form1 : Form
    {
//        IWebDriver Browser;

        public string fileProxyName = @"";
        public int MaxViews;
        public string razdelitel;
        public List<string> ProxyIp = new List<string>();
        public List<int> ProxyPort = new List<int>();
        public List<string> ProxyLogin = new List<string>();
        public List<string> ProxyPassword  =new List<string>();


        public Form1()
        {
            InitializeComponent();
            LabelMaxViewText();
            openFileDialog1.Filter = "TextDoc | *.txt";
            

        }

        private void button1_Click(object sender, EventArgs e)
        {


            LoadBrauzer();

          

        }


        public void LoadBrauzer()
        {

            for (int i = 0; 0 < MaxViews; i++)
            {



                IWebDriver Browser = new ChromeDriver();


                ChromeOptions options = new ChromeOptions();
                options.AddArgument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0");
                //       options.AddArgument("ignore-certificate-errors");
                options.AddArguments("--disable-blink-features");
                options.AddArgument("--disable-blink-features=AutomationControlled");
                options.AddExcludedArgument("enable-automation");
                options.AddArguments("--disable-infobars");
                options.AddHttpProxy(ProxyIp[i], ProxyPort[i], ProxyPassword[i], ProxyLogin[i]);
                //  options.AddArguments("headless"); // hide

                Browser = new OpenQA.Selenium.Chrome.ChromeDriver(options);
                Browser.Manage().Window.Maximize();
                Browser.Navigate().GoToUrl("https://MESITE.ru");
                Browser.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
                CheckAcceptOption( Browser);
                IWebElement FindTextBoxSearch = Browser.FindElement(By.ClassName("char-header-search-module__input"));
                FindTextBoxSearch.SendKeys(textBoxFindVideo.Text + OpenQA.Selenium.Keys.Enter);
                OpenVideo(Browser);
            }
        }


        private void CheckAcceptOption(IWebDriver Browser)
        {
            Actions actionProvider = new Actions(Browser);
            IWebElement FindOption = Browser.FindElement(By.CssSelector(".char-base-button-module__button.char-base-button-module__contained-accent.char-base-button-module__pointerCursor.char-base-button-module__regular"));
            if (FindOption != null)
            {
                actionProvider.Click(FindOption).Perform();
            }
            else return;
        }


        private void OpenVideo(IWebDriver Browser)
        {
            Actions actionProvider = new Actions(Browser);
            IWebElement FindVideo = Browser.FindElement(By.ClassName("pen-h-card-inline__image-wrapper"));
            actionProvider.Click(FindVideo).Perform();

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void LabelMaxViewText()
        {
            LabelMax.Text = "Max = " + MaxViews.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                fileProxyName = openFileDialog1.FileName;
            }
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            string[] split;
            StreamReader Filen = new StreamReader(fileProxyName);
            while ((razdelitel = Filen.ReadLine()) != null)
            {
               
                split = razdelitel.Split(':');
                var timeIpProxy = split[0];
                var timePortProxy = split[1];
                var timeProxyLogin = split[2];
                var timeProxyPassword = split[3];
                ProxyIp.Add(timeIpProxy);
                int x = Int32.Parse(timePortProxy);
                ProxyPort.Add(x);
                ProxyLogin.Add(timeProxyLogin);
                ProxyPassword.Add(timeProxyPassword);
                MaxViews++;
            }
            LabelMaxViewText();
            Filen.Close();
        }
    }
}

I've heard about selenium grid.我听说过 selenium 网格。 There must be a way to open as many tabs as I have a proxy, right?必须有一种方法可以打开与我有代理一样多的选项卡,对吗? I'm trying to implement this through for.我正在尝试通过 for 来实现这一点。 My list contains proxy data and it is convenient to take them in a loop, and if you run everything at once, how do I track changes?我的列表包含代理数据,循环使用它们很方便,如果一次运行所有内容,我如何跟踪更改? I don't understand....我不明白....

What I did for this issue was create a WinForm to have a UI for running my tests.我为这个问题所做的是创建一个 WinForm 来拥有一个用于运行我的测试的 UI。 Then at the click of a button id call a function that ran my test.然后单击按钮 id 调用运行我的测试的 function。 If you did it like I did(see below), itll open an instance of the test for every click(or you can put it in a loop to open as many as needed).如果你像我一样做(见下文),它会为每次点击打开一个测试实例(或者你可以将它放在一个循环中以根据需要打开多个)。 The key is to not make the task run async or itll wait for one test to finish before opening another.关键是不要让任务异步运行,否则它会等待一个测试完成后再打开另一个测试。 This may not be exactly what you need, but this is how I was able to accomplish it.这可能不是您所需要的,但这就是我能够完成它的方式。 Shouldnt need proxies or multiple ports or anything.不应该需要代理或多个端口或任何东西。

        private void Upload_Click(object sender, EventArgs e)
        {
            Task.Run(() => TestFunction(Param1, Param2, Param3));
        }

Example Function示例 Function

        public void TestFunction(Param1, Param2, Param3)
        {
            //Function to Open Browser, You can call your browser however youd like
            IWebDriver driver = InitBrowser("chrome");
            string LandingPage = "https://google.com";
            driver.Url = LandingPage;

            driver.Quit();
        }

You can see how it opens multiple instances in the image below您可以在下图中看到它如何打开多个实例

这是我运行的测试如何发挥作用的图像

The other answer didn't work for me unfortunately.Based on an answer to a similar question, I was able to configure parallel run of Selenium instances like this:不幸的是,另一个答案对我不起作用。基于对类似问题的回答,我能够像这样配置 Selenium 实例的并行运行:

List<Task> tasks = new();
foreach (var someObject in listOfObjects)
{
    tasks.Add(Class.SomeMethod(arg1, arg2, arg3));
}
await Task.WhenAll(tasks);

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

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