滑动验证码如下:
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