-
private void SeleniumVertifyCode(Uri uri)
-
{
-
var options = new OpenQA.Selenium.Chrome.ChromeOptions();
-
//不显示浏览器UI窗口
-
options.AddArgument("-headless");
-
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();
-
}
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有