zoukankan      html  css  js  c++  java
  • c#使用selenium过滑动验证码

    滑动验证码如下:

    1、vs引入以下三个包(.net core 3.1):

    2、c#引用:

    private void SeleniumVertifyCode(Uri uri)
            {
    var options = new OpenQA.Selenium.Chrome.ChromeOptions();
                //不显示浏览器UI窗口
                options.AddArgument("-headless");
                //设置浏览器大小避免无头模式下元素越界异常
                options.AddArgument("--window-size=1920,1050");
                //减少headless模式下日志
                options.AddArgument("log-level=3");
                using IWebDriver driver = new OpenQA.Selenium.Chrome.ChromeDriver(options);
                //先设置uri
                driver.Navigate().GoToUrl(uri);
                var cookie = driver.Manage().Cookies;
                //再添加cookie
                cookie.AddCookie(new Cookie("name", "value", ".com", "/", null));
                //再次访问验证码uri
                driver.Navigate().GoToUrl(uri);
                //反爬:设置windows.navigate.webdrive的值为undefine
                driver.ExecuteJavaScript("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})");
    //查看网页源码
    //var source = driver.PageSource;
                //找到滑块元素
                var slide = driver.FindElement(By.CssSelector("#nc_1_n1z"));
                var verifyContainer = driver.FindElement(By.CssSelector(".nc-lang-cnt"));
                var width = verifyContainer.Size.Width;
                var action = new Actions(driver);
                //点击并按住滑块元素
                action.ClickAndHold(slide).Perform();
                Random random = new Random();
                int offset = 0;
                //模仿人工滑动
                const int minOffset = 10;
                const int maxOffset = 30;
                while (width > offset)
                {
                    offset += random.Next(minOffset, maxOffset);
                    action.MoveByOffset(offset, 0).Perform();
                    var code = driver.FindElement(By.CssSelector(".nc-lang-cnt")).Text;
                    if (code.Contains("验证通过"))
                    {
                        break;
                    }
                    System.Threading.Thread.Sleep(offset * minOffset);
                }
                //点击验证按钮
                action.Click(driver.FindElement(By.CssSelector("#verify"))).Perform();
                //退出webdriver
                driver.Quit();
            }

    反爬参考:https://blog.csdn.net/weixin_44500833/article/details/105263822

  • 相关阅读:
    Python 用SMTP发送邮件
    Python 用IMAP接收邮件
    E-mail Composition and Decoding
    用Python实现gmail邮箱服务,实现两个邮箱之间的绑定(中)
    【日志】-2013.10.31
    21本计算机数学相关的免费电子书【转】
    WordPress搭建Personal Blog【转】
    一句话点亮你的人生
    【日志】-2013.10.28
    转载-smarty教程(基本语法)
  • 原文地址:https://www.cnblogs.com/Zdelta/p/14122310.html
Copyright © 2011-2022 走看看