C#实现定时抢讲座
研究生期间在定时问卷星上一直抢不到讲座,参考了很多大佬的经验,写了个界面可以挂上帮抢,用起来很好,记下笔记。
c# VS2019安装的NuGet包
主要通过这三个包实现网页操控。
安装后可以手动或者自动添加引用
核心代码
主要参考的这篇大佬的文章,给了我很多启发,非常好的反爬爬方法:
C#.net下ChromeDriver自动化测试初体验.
在chromedriver打开的浏览器里存在变量window.navigator.webdriver,容易被网站检测到。尤其是问卷星的验证,一旦监测到window.navigator.webdriver==true,验证就会不通过。反制方法是使用chrome远程调试,在命令行中执行下面的命令:
chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\AutomationProfile"
通过参数启动chrome,打开远程调试端口,以下代码接管:
ChromeOptions opt = new ChromeOptions();
opt.DebuggerAddress = "127.0.0.1:9222";
ChromeDriver driver = new ChromeDriver(@"Q:\chrome\", opt);//参数配置见下一步
driver.ExecuteAsyncScript("alert(0);");
//有时候谷歌浏览器会弹出消息框,必须先关闭该消息框然后才能继续进行操作
driver.SwitchTo().Alert().Accept();
//打开链接即可
driver.Navigate().GoToUrl("https://www.wjx.cn/vj/PhjMxZu.aspx");
ChromeDriver()函数的参数可以调整,第一个参数是chromedriver.exe的Directory,第二个参数是options,可以设置如下:
ChromeDriverService service = ChromeDriverService.CreateDefaultService(Environment.CurrentDirectory);
//隐藏chromedriver的启动黑框
service.HideCommandPromptWindow = true;
ChromeOptions opt = new ChromeOptions();
//opt.AddArgument("no-sandbox");
// GPU加速可能会导致Chrome出现黑屏及CPU占用率过高,所以禁用
opt.AddArgument("--disable-gpu");
opt.DebuggerAddress = "127.0.0.1:9222";
ChromeDriver driver = new ChromeDriver(service,opt);//"C:\Users\Lenovo\source\repos\jzGetV.4\bin\Debug"
小技巧:在代码中,可以通过c#自动调用执行cmd命令行:
private void excuteCmd1()
{
string textChrome = C:\Program Files\Google\Chrome\Application;//chrome。exe在电脑里的安装位置
string strInput1 = @"cd/d "+ textChrome;
string strInput2 = "chrome.exe --remote-debugging-port=9222 --user-data-dir=\"C:\\selenum\\AutomationProfile\"";
Process p = new Process();
//设置要启动的应用程序
p.StartInfo.FileName = "cmd.exe";
//是否使用操作系统shell启动
p.StartInfo.UseShellExecute = false;
// 接受来自调用程序的输入信息
p.StartInfo.RedirectStandardInput = true;
//输出信息
p.StartInfo.RedirectStandardOutput = true;
// 输出错误
p.StartInfo.RedirectStandardError = true;
//不显示程序窗口
p.StartInfo.CreateNoWindow = true;
//启动程序
p.Start();
//向cmd窗口发送输入信息
p.StandardInput.WriteLine(strInput1);
//p.StandardInput.AutoFlush = true;
p.StandardInput.WriteLine(strInput2);
//string strOuput = p.StandardOutput.ReadToEnd();
//等待程序执行完退出进程
//p.WaitForExit();
p.Close();
//Console.WriteLine(strOuput);
//Console.ReadKey();
}
每次运行完,chrome浏览器和chromedriver.exe总是残留在后台进程中,原因是没有在程序执行完之后推出chromedriver.exe,需要加上:
driver.Quit();
也有些旁门左道,可以在cmd中执行如下命令,清理进程,一劳永逸:
taskkill /f /im chromedriver.exe
taskkill /f /im chrome.exe
后面再有就是页面操作问题了,很多博文都有介绍,比如这位大佬的总结:
C#爬虫(03):使用Selenium
附上我完成的界面:
提前至少1分钟,填好网址、时间和个人信息,点击“开始干活”,就可以开抢讲座了,做签到表上最靠前的靓仔。
最后附上程序安装包,直接安装就可以使用,有需要的小伙伴自取
https://download.csdn.net/download/weixin_46017840/44371402
(完)