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

发布于 2025-01-21 02:28:16 字数 5099 浏览 0 评论 0原文

我希望我的程序能够同时打开多个浏览器实例并执行操作。但我遇到了一个问题,就是所有的动作都是依次执行的。我有一个代理服务器列表和来自它们的数据,如何使多个浏览器实例同时打开并开始工作?

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();
        }
    }
}

我听说过硒网格。一定有办法打开与我有代理一样多的选项卡,对吗?我正在尝试通过 for 来实现这一点。我的列表包含代理数据,可以方便地循环使用它们,如果您一次运行所有内容,我如何跟踪更改?我不明白....

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. There must be a way to open as many tabs as I have a proxy, right? I'm trying to implement this through 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....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

む无字情书 2025-01-28 02:28:16

不幸的是,另一个答案对我不起作用。基于对类似问题的答案,我能够配置这样的硒实例的并行运行:

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

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:

List<Task> tasks = new();
foreach (var someObject in listOfObjects)
{
    tasks.Add(Class.SomeMethod(arg1, arg2, arg3));
}
await Task.WhenAll(tasks);
节枝 2025-01-28 02:28:16

我为这个问题所做的是创建一个winform,以使用UI进行测试。然后,在单击“按钮ID”时,请调用一个函数进行我的测试。如果您像我一样(请参阅下文)进行操作,则每次点击打开一个测试实例(或者您可以将其放入循环中以根据需要打开尽可能多的时间)。关键是不要使任务运行异步或IT将等待一个测试完成,然后再打开另一个测试。这可能不是您所需要的,但这就是我能够完成它的方式。不需要代理或多个端口或任何东西。

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

示例函数

        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();
        }

图像中打开多个实例

您可以查看如何在下面的 。

    public static IWebDriver InitBrowser(string browserName)
    {
        switch (browserName)
        {
            case "chrome":
                {
                    ChromeOptions co = new ChromeOptions();
                    co.AddArguments("--incognito", "--window-size=1920,1080", "--applicationCacheDisabled", "--applicationCookiesDisabled", "--disable-plugins", "--HideCommandPromptWindow");
                    IWebDriver driver = new ChromeDriver(co);
                    return driver;
                }
        }
        return null;
    }

What I did for this issue was create a WinForm to have a UI for running my tests. Then at the click of a button id call a function that ran my test. 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

        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

Here is an image of how it plays out for a test I run

EDIT: Someone asked for the InitBrowser loop, it looks like this:

    public static IWebDriver InitBrowser(string browserName)
    {
        switch (browserName)
        {
            case "chrome":
                {
                    ChromeOptions co = new ChromeOptions();
                    co.AddArguments("--incognito", "--window-size=1920,1080", "--applicationCacheDisabled", "--applicationCookiesDisabled", "--disable-plugins", "--HideCommandPromptWindow");
                    IWebDriver driver = new ChromeDriver(co);
                    return driver;
                }
        }
        return null;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文