通过CefSharp实现浏览器自动输入自动点击按钮等
本程序基于CefSharp实现自动打开一个网站,自动输入账号密码自动注册。然后跳转到商品页自动输入评论的内容然后提交。完全模拟人为在浏览器的所有操作,包括自动输入,自动点击等操作。
本解决方案可以应用于网络爬虫,刷单,刷评论,参与自动秒杀活动。抢票程序等等。
最终效果如下:
cefsharp是一个在c#中使用Chrome浏览器内核实现浏览器功能的插件,类似于c#中的WebBrowser功能。
主要代码:
1、引用
<wpf:ChromiumWebBrowser x:Name="webBrowser" Address="https://www.walmart.com/account/login"/>
2、执行JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public async void EvaluateJavaScript( string s, bool addCommonJs = false ) { try { if (addCommonJs) { s = commonJs + s; } var response = await webBrowser.EvaluateScriptAsync(s); if (response.Success && response.Result is IJavascriptCallback) { response = await ((IJavascriptCallback)response.Result).ExecuteAsync( "This is a callback from EvaluateJavaScript" ); } var EvaluateJavaScriptResult = response.Success ? (response.Result ?? "null" ) : response.Message; } catch (Exception e) { MessageBox.Show( "Error while evaluating Javascript: " + e.Message, "Error" , MessageBoxButton.OK, MessageBoxImage.Error); } } |
3、设置cookie
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public static void SetCefCookies( string url, CookieCollection cookies) { //Cef.GetGlobalCookieManager().SetStoragePath(Environment.CurrentDirectory, true); foreach (System.Net.Cookie c in cookies) { var cookie = new CefSharp.Cookie { Creation = DateTime.Now, Domain = c.Domain, Name = c.Name, Value = c.Value, Expires = c.Expires }; Task< bool > task = Cef.GetGlobalCookieManager().SetCookieAsync(url, cookie); while (!task.IsCompleted) { continue ; } bool b = task.Result; } } |
4、获取当前页面的html源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | private string GetHTMLFromWebBrowser() { // call the ViewSource method which will open up notepad and display the html. // this is just so I can compare it to the html returned in GetSourceAsync() // This is displaying all the html code (including child frames) //webBrowser.GetBrowser().MainFrame.ViewSource(); // Get the html source code from the main Frame. // This is displaying only code in the main frame and not any child frames of it. Task<String> taskHtml = webBrowser.GetBrowser().MainFrame.GetSourceAsync(); string response = taskHtml.Result; return response; } |
5、拦截json请求结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public class DefaultResourceHandler : ResourceRequestHandler { public event EventHandler<JsonResponseHandlerEventArgs> json_response_handler; private Dictionary< ulong , MemoryStreamResponseFilter> responseDictionary = new Dictionary< ulong , MemoryStreamResponseFilter>(); public DefaultResourceHandler() { } public DefaultResourceHandler(EventHandler<JsonResponseHandlerEventArgs> json_response_handler) { this .json_response_handler = json_response_handler; } protected override IResponseFilter GetResourceResponseFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response) { if (response.MimeType.Equals( "application/json" , StringComparison.OrdinalIgnoreCase) || (response.Headers[ "Content-Type" ] != null && response.Headers[ "Content-Type" ].ToLower().Contains( "application/json" ))) { return JsonResponseFilter.CreateFilter(request.Identifier.ToString()); } return null ; } protected override void OnResourceLoadComplete(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength) { var filter = JsonResponseFilter.GetFileter(request.Identifier.ToString()) as JsonResponseFilter; if (filter != null ) { var encode = ! string .IsNullOrEmpty(response.Charset) ? Encoding.GetEncoding(response.Charset) : Encoding.UTF8; using ( var read = new StreamReader(filter.GetStream(), encode)) { //获取到的json内容 var text = read.ReadToEnd(); json_response_handler?.Invoke(response, new JsonResponseHandlerEventArgs(request, response, text)); Trace.WriteLine(response.MimeType + "=>" + request.Url + "::" + text); } } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?