在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C# 模拟http 发包请求工具源码(可设置代理IP)

C# 模拟http 发包请求工具源码(可设置代理IP)

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:3.53M
  • 下载次数:93
  • 浏览次数:2712
  • 发布时间:2016-02-04
  • 实例类别:C#语言基础
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: IP 代理 http C# c

同类人气实例

实例介绍

【实例简介】

【实例截图】

【核心代码】


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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
using System;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.Win32;
using mshtml;
 
namespace SpiderTool
{
    #region COM Interfaces
 
    [ComImport,
    Guid("00000112-0000-0000-C000-000000000046"),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IOleObject
    {
        void SetClientSite(IOleClientSite pClientSite);
        void GetClientSite(IOleClientSite ppClientSite);
        void SetHostNames(object szContainerApp, object szContainerObj);
        void Close(uint dwSaveOption);
        void SetMoniker(uint dwWhichMoniker, object pmk);
        void GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk);
        void InitFromData(IDataObject pDataObject, bool
        fCreation, uint dwReserved);
        void GetClipboardData(uint dwReserved, IDataObject ppDataObject);
        void DoVerb(uint iVerb, uint lpmsg, object pActiveSite,
        uint lindex, uint hwndParent, uint lprcPosRect);
        void EnumVerbs(object ppEnumOleVerb);
        void Update();
        void IsUpToDate();
        void GetUserClassID(uint pClsid);
        void GetUserType(uint dwFormOfType, uint pszUserType);
        void SetExtent(uint dwDrawAspect, uint psizel);
        void GetExtent(uint dwDrawAspect, uint psizel);
        void Advise(object pAdvSink, uint pdwConnection);
        void Unadvise(uint dwConnection);
        void EnumAdvise(object ppenumAdvise);
        void GetMiscStatus(uint dwAspect, uint pdwStatus);
        void SetColorScheme(object pLogpal);
    }
 
    [ComImport,
     Guid("00000118-0000-0000-C000-000000000046"),
     InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IOleClientSite
    {
        void SaveObject();
        void GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk);
        void GetContainer(object ppContainer);
        void ShowObject();
        void OnShowWindow(bool fShow);
        void RequestNewObjectLayout();
    }
 
    [ComImport,
    Guid("6d5140c1-7436-11ce-8034-00aa006009fa"),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    ComVisible(false)]
    public interface IServiceProvider
    {
 
        [return: MarshalAs(UnmanagedType.I4)]
        [PreserveSig]
        int QueryService(ref Guid guidService, ref Guid riid, out IntPtr
        ppvObject);
    }
 
    [ComImport, Guid("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B"),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    ComVisible(false)]
    public interface IAuthenticate
    {
        [return: MarshalAs(UnmanagedType.I4)]
        [PreserveSig]
        int Authenticate(ref IntPtr phwnd,
        ref IntPtr pszUsername,
        ref IntPtr pszPassword
        );
    }
 
 
    #endregion
 
    public static class WebBrowserExtend
    {
        #region  代理安培版本
 
        [DllImport(@"wininet",
        SetLastError = true,
        CharSet = CharSet.Auto,
        EntryPoint = "InternetSetOption",
        CallingConvention = CallingConvention.StdCall)]
        public static extern bool InternetSetOption
        (
        int hInternet,
        int dmOption,
        IntPtr lpBuffer,
        int dwBufferLength
        );
 
        /// <summary>
        /// 设置代理
        /// </summary>
        /// <param name="webBrowser"></param>
        /// <param name="ip"></param>
        public static void SetProxy(this WebBrowser webBrowser, string ip)
        {
            //打开注册表
            RegistryKey regKey = Registry.CurrentUser;
            string SubKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
            RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);
            //更改健值,设置代理,
            optionKey.SetValue("ProxyEnable", 1);
            optionKey.SetValue("ProxyServer", ip);
            //激活代理设置
            InternetSetOption(0, 39, IntPtr.Zero, 0);
            InternetSetOption(0, 37, IntPtr.Zero, 0);
        }
 
        /// <summary>
        /// 取消代理
        /// </summary>
        /// <param name="webBrowser"></param>
        public static void Cancelproxy(this WebBrowser webBrowser)
        {
            //打开注册表
            RegistryKey regKey = Registry.CurrentUser;
            const string subKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
            RegistryKey optionKey = regKey.OpenSubKey(subKeyPath, true);
            //更改健值,取消代理
            if (optionKey != null) optionKey.SetValue("ProxyEnable", 0);
            //激活代理设置
            InternetSetOption(0, 39, IntPtr.Zero, 0);
            InternetSetOption(0, 37, IntPtr.Zero, 0);
        }
 
        #endregion
 
        #region 代理
        public static Guid IID_IAuthenticate = new Guid("79eac9d0-baf9-11ce-8c82-00aa004ba90b");
        public const int INET_E_DEFAULT_ACTION = unchecked((int)0x800C0011);
        public const int S_OK = unchecked((int)0x00000000);
 
        #region IOleClientSite Members
 
 
        #endregion
 
        #region IServiceProvider Members
 
        public static int QueryService(this WebBrowser webBrowser, ref Guid guidService, ref Guid riid, out IntPtr ppvObject)
        {
            int nRet = guidService.CompareTo(IID_IAuthenticate); // Zero returned if the compared objects are equal
            if (nRet == 0)
            {
                nRet = riid.CompareTo(IID_IAuthenticate); // Zero returned if the compared objects are equal
                if (nRet == 0)
                {
                    ppvObject = Marshal.GetComInterfaceForObject(webBrowser, typeof(IAuthenticate));
                    return S_OK;
                }
            }
            ppvObject = new IntPtr();
            return INET_E_DEFAULT_ACTION;
        }
 
        #endregion
 
        #region IAuthenticate Members
 
        private static string userName = "";
        private static string passWord = "";
 
        public static int Authenticate(this WebBrowser webBrowser, ref IntPtr phwnd, ref IntPtr pszUsername, ref IntPtr pszPassword)
        {
            IntPtr sUser = Marshal.StringToCoTaskMemAuto(userName);
            IntPtr sPassword = Marshal.StringToCoTaskMemAuto(passWord);
 
            pszUsername = sUser;
            pszPassword = sPassword;
            return S_OK;
        }
 
        #endregion
 
 
        public struct Struct_INTERNET_PROXY_INFO
        {
            public int dwAccessType;
            public IntPtr proxy;
            public IntPtr proxyBypass;
        };
        [DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);
 
        private static void RefreshIESettings(this WebBrowser webBrowser, string strProxy)
        {
            const int INTERNET_OPTION_PROXY = 38;
            const int INTERNET_OPEN_TYPE_PROXY = 3;
 
            Struct_INTERNET_PROXY_INFO struct_IPI;
 
            // Filling in structure
            struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
            struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy);
            struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local");
 
            // Allocating memory
            IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI));
 
            // Converting structure to IntPtr
            Marshal.StructureToPtr(struct_IPI, intptrStruct, true);
 
            bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI));
        }
 
 
 
        #endregion
 
        #region 委托
        private delegate void NoParam();
        private delegate void OneStringParam(string str);
        private delegate void TwoSstringParam(string str1, string str2);
        private delegate void ThreeStringParam(string str1, string str2, string str3);
        private delegate void FourStringParam(string str1, string str2, string str3, string str4);
        private delegate void FiveStringparam(string str1, string str2, string str3, string str4, string str5);
        //private delegate void OnParam();
        private delegate Bitmap ReturnBitMapOnParam();
        private delegate HtmlDocument GetHtmlDocumentDelegate();
        private delegate string GetStringDelegate();
        private delegate bool GetBoolDelegate();
        private delegate WebBrowserReadyState GetWebBrowserReadyState();
        #endregion
 
        #region 屏蔽弹框
 
        private const string Js = "window.alert = null;\r\nwindow.confirm = null;\r\nwindow.open = null;\r\nwindow.showModalDialog = null;";
 
 
 
        #endregion
 
 
        #region 获得页面htmlSource
 
        /// <summary>
        /// 当前页面的Document(异步成员)
        /// </summary>
        public static HtmlDocument Document(this WebBrowser webBrowser)
        {
 
            if (webBrowser.InvokeRequired)//控件的 Handle 是在与调用线程不同的线程上创建的(说明您必须通过 Invoke 方法对控件进行调用),为 true;否则为 false。
            {
                IAsyncResult iar = webBrowser.BeginInvoke(new GetHtmlDocumentDelegate(delegate() { return webBrowser.Document; }));
                return (HtmlDocument)webBrowser.EndInvoke(iar);
            }
            else
            {
                return webBrowser.Document;
            }
 
            //set { _WebHtml = value; }
        }
 
        /// <summary>
        /// 当前页面的HtmlSource(异步成员)
        /// </summary>
        public static string DocumentText(this WebBrowser webBrowser)
        {
 
            if (webBrowser.InvokeRequired)//控件的 Handle 是在与调用线程不同的线程上创建的(说明您必须通过 Invoke 方法对控件进行调用),为 true;否则为 false。
            {
                IAsyncResult iar = webBrowser.BeginInvoke(new GetStringDelegate(delegate() { return webBrowser.DocumentText; }));
                return webBrowser.EndInvoke(iar).ToString();
            }
            else
            {
                return webBrowser.DocumentText;
            }
 
        }
 
        /// <summary>
        /// 当前页面的HtmlSource(异步成员)
        /// </summary>
        public static string InnerBodyHtml(this WebBrowser webBrowser)
        {
 
            if (webBrowser.InvokeRequired)//控件的 Handle 是在与调用线程不同的线程上创建的(说明您必须通过 Invoke 方法对控件进行调用),为 true;否则为 false。
            {
                IAsyncResult iar = webBrowser.BeginInvoke(new GetStringDelegate(() => InnerBodyHtml(webBrowser)));
                return webBrowser.EndInvoke(iar).ToString();
            }
            else
            {
                try
                {
                    HtmlDocument document = webBrowser.Document;
                    if (document != null) if (document.Body != null) return document.Body.InnerHtml;
 
                }
                catch (Exception)
                {
 
 
                }
                return "";
 
 
            }
        }
 
        /// <summary>
        /// 得到当前页面的Html如果页面没加载完.会自动等待(异步成员)
        /// </summary>
        public static string WaitInnerBodyHtml(this WebBrowser webBrowser)
        {
 
            while (webBrowser.ReadyState != WebBrowserReadyState.Complete || IsBusy(webBrowser))
            {
                System.Threading.Thread.Sleep(50);
            }
            return InnerBodyHtml(webBrowser);
 
        }
 
        /// <summary>
        /// 得到当前控件的状态(异步成员)
        /// </summary>
        public static WebBrowserReadyState ReadyState(this WebBrowser webBrowser)
        {
 
            if (webBrowser.InvokeRequired)
            {
                IAsyncResult iar = webBrowser.BeginInvoke(new GetWebBrowserReadyState(() => ReadyState(webBrowser)));
                return (WebBrowserReadyState)webBrowser.EndInvoke(iar);
            }
            else
            {
                return webBrowser.ReadyState;
            }
 
        }
 
        /// <summary>
        /// 指示当前控件是否在加载新文档(异步成员)
        /// </summary>
        public static bool IsBusy(this WebBrowser webBrowser)
        {
 
            if (webBrowser.InvokeRequired)
            {
                IAsyncResult iar = webBrowser.BeginInvoke(new GetBoolDelegate(() => IsBusy(webBrowser)));
                return (bool)webBrowser.EndInvoke(iar);
            }
            else
            {
                return IsBusy(webBrowser);
            }
 
        }
 
        #endregion
 
        #region 内存回收
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        /// <summary>
        /// 释放内存
        /// </summary>
        public static void ClearMemory()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
            }
        }
        #endregion
 
 
 
        #region 控制页面元素  Js版本已注释不用
        //        /// <summary>
        //        /// 根据ID设置TextBox的value
        //        /// </summary>
        //        /// <param name="webkitForm"></param>
        //        /// <param name="id"></param>
        //        /// <param name="value"></param>
        //        public void SetValueByID(string id, string value)
        //        {
        //            string strjs = @"
        //            document.getElementById('{0}').focus();
        //            document.getElementById('{0}').value = '{1}';";
        //            EvaluateJScript(strjs, id, value);
        //        }
        //        /// <summary>
        //        /// 根据标签设置Value
        //        /// </summary>
        //        /// <param name="webkitForm"></param>
        //        /// <param name="tagName"></param>
        //        /// <param name="AttributeName"></param>
        //        /// <param name="AttributeValue"></param>
        //        /// <param name="innerText"></param>
        //        public void SetValueByAttribute(string tagName, string AttributeName, string AttributeValue, string innerText, string value)
        //        {
        //            string strjs = @"
        //            var hes = document.getElementsByTagName('{0}');
        //            for (var i = 0; i < hes.length; i  ) {{
        //                var he = hes[i];
        //                if (he['{1}'] == 'undefined')
        //                    continue;
        //                if (he['{1}'] == null)
        //                    continue;
        //                if (he.innerText == 'undefined')
        //                    continue;
        //                if (he.innerText == null)
        //                    continue;
        //                if (he['{1}'] == '{2}' && he.innerText.indexOf('{3}')>=0) {{
        //                    he.focus();
        //                    he.innerText = '{4}';
        //                    he.focus();
        //                    break;
        //                }}
        //            }}
        //";
        //            EvaluateJScript(strjs, tagName, AttributeName, AttributeValue, innerText, value);
        //        }
        //        /// <summary>
        //        /// 根据ID点击按钮
        //        /// </summary>
        //        /// <param name="webkitForm"></param>
        //        /// <param name="id"></param>
        //        public void ClickByID(string id)
        //        {
        //            string strjs = "document.getElementById('{0}').click();";
        //            EvaluateJScript(strjs, id);
        //        }
        //        /// <summary>
        //        /// 根据标签点击按钮
        //        /// </summary>
        //        /// <param name="tagName"></param>
        //        /// <param name="AttributeName"></param>
        //        /// <param name="AttributeValue"></param>
        //        /// <param name="innerText"></param>
        //        public void ClickByAttribute(string tagName, string AttributeName, string AttributeValue, string innerText)
        //        {
        //            string strjs = @"
        //            var hes = document.getElementsByTagName('{0}');
        //            for (var i = 0; i < hes.length; i  ) {{
        //                var he = hes[i];
        //                if (he['{1}'] == 'undefined')
        //                    continue;
        //                if (he['{1}'] == null)
        //                    continue;
        //                if (he.innerText == 'undefined')
        //                    continue;
        //                if (he.innerText == null)
        //                    continue;
        //                if (he['{1}'] == '{2}' && he.innerText.indexOf('{3}')>=0) {{
        //                    he.click();
        //                    break;
        //                }}
        //            }}
        //";
        //            EvaluateJScript(strjs, tagName, AttributeName, AttributeValue, innerText);
        //        }
 
        //        private delegate void DelEvaluateJs(string strJS, params object[] args);
        //        /// <summary>
        //        /// 执行js
        //        /// </summary>
        //        /// <param name="strJS"></param>
        //        private void EvaluateJScript(string strJS, params object[] args)
        //        {
        //            if (this.InvokeRequired)
        //            {
        //                this.BeginInvoke(new DelEvaluateJs(EvaluateJScript), strJS, args);
        //            }
        //            else
        //            {
        //                try
        //                {
        //                    if (args.Length > 0)
        //                        strJS = string.Format(strJS, args);
        //                    //新建Html标记
        //                    HtmlElement he = this.Document.CreateElement("script");
        //                    he.SetAttribute("type", "text/javascript");
        //                    he.SetAttribute("text", strJS);
        //                    //将元素嵌入到动态网页中
        //                    this.Document.Body.AppendChild(he);
        //                }
        //                catch
        //                { }
        //            }
        //        }
 
        #endregion
 
        #region  控制页面元素
        /// <summary>
        /// 根据ID设置TextBox的value
        /// </summary>
        /// <param name="id"></param>
        /// <param name="value"></param>
        public static void SetValueById(this WebBrowser webBrowser, string id, string value)
        {
            if (webBrowser.InvokeRequired)
            {
                IAsyncResult ir = webBrowser.BeginInvoke(new Action(() => SetValueById(webBrowser, id, value)));
                webBrowser.EndInvoke(ir);
            }
            else
            {
                HtmlDocument doc = webBrowser.Document;
                if (doc != null)
                {
                    HtmlElement ele = FindControlById(webBrowser, id, doc.All);
                    if (ele != null)
                    {
                        HTMLInputElement hie = ele.DomElement as HTMLInputElement;
                        if (hie != null)
                        {
                            hie.value = value;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 根据标签设置Value
        /// </summary>
        /// <param name="tagName"></param>
        /// <param name="AttributeName"></param>
        /// <param name="AttributeValue"></param>
        /// <param name="innerText"></param>
        /// <param name="value"></param>
        public static void SetValueByAttribute(this WebBrowser webBrowser, string tagName, string AttributeName, string AttributeValue, string innerText, string value)
        {
            if (webBrowser.InvokeRequired)
            {
                IAsyncResult ir = webBrowser.BeginInvoke(new Action(() => SetValueByAttribute(webBrowser, tagName, AttributeName, AttributeValue, innerText, value)));
                webBrowser.EndInvoke(ir);
            }
            else
            {
                //if (tagName == "textarea")
                //{
                //HTMLInputTextElement hae = FindControlByAttValue(tagName, AttributeName, AttributeValue, innerText, this.Document.All).DomElement as HTMLInputTextElement;
                //hae.value = value;
                //}
                //else if (tagName == "input")
                //{
                if (webBrowser.Document != null)
                {
                    HTMLInputElement hie = FindControlByAttValue(webBrowser, tagName, AttributeName, AttributeValue, innerText, webBrowser.Document.All).DomElement as HTMLInputElement;
                    if (hie != null) hie.value = value;
                }
                //}
            }
        }
        /// <summary>
        /// 根据ID点击按钮
        /// </summary>
        /// <param name="id"></param>
        public static void ClickByID(this WebBrowser webBrowser, string id)
        {
            if (webBrowser.InvokeRequired)
            {
                IAsyncResult ir = webBrowser.BeginInvoke(new Action(() => ClickByID(webBrowser, id)));
                webBrowser.EndInvoke(ir);
            }
            else
            {
                if (webBrowser.Document != null)
                {
                    HTMLInputElement hie = FindControlById(webBrowser, id, webBrowser.Document.All).DomElement as HTMLInputElement;
                    HTMLAnchorElement hae = FindControlById(webBrowser, id, webBrowser.Document.All).DomElement as HTMLAnchorElement;
                    if (hie != null)
                    {
                        hie.click();
                    }
                    else if (hae != null)
                    {
                        hae.click();
                    }
                }
            }
        }
        /// <summary>
        /// 根据标签点击按钮
        /// </summary>
        /// <param name="tagName"></param>
        /// <param name="AttributeName"></param>
        /// <param name="AttributeValue"></param>
        /// <param name="innerText"></param>
        public static void ClickByAttribute(this WebBrowser web, string tagName, string AttributeName, string AttributeValue, string innerText)
        {
            if (web.InvokeRequired)
            {
                IAsyncResult ir = web.BeginInvoke(new Action(() => ClickByAttribute(web, tagName, AttributeName, AttributeValue, innerText)));
                web.EndInvoke(ir);
            }
            else
            {
                if (tagName.ToLower() == "a")
                {
                    if (web.Document != null)
                    {
                        HtmlElement he = FindControlByAttValue(web, tagName, AttributeName, AttributeValue, innerText, web.Document.All);
                        if (he == null)
                        {
                            return;
                        }
                        HTMLAnchorElement ae = he.DomElement as HTMLAnchorElement;
                        if (ae != null) ae.click();
                    }
                    //HTMLAnchorElement hae = he.DomElement as HTMLAnchorElement;
                    //if (hae != null)
                    //{
                    //    //if (hae.href != null && hae.href.StartsWith("http"))
                    //    //{
                    //    hae.click();
                    //    //}
                    //    //string onclick = Regex.Match(hae.outerHTML, "(?<=<A onclick=). ?(?=title)").Value;
                    //    //this.Document.InvokeScript(onclick);
                    //}
                }
                else if (tagName.ToLower() == "input")
                {
                    if (web.Document != null)
                    {
                        HtmlElement he = FindControlByAttValue(web, tagName, AttributeName, AttributeValue, innerText,
                            web.Document.All);
                        if (he != null)
                        {
                            HTMLInputElement hae = he.DomElement as HTMLInputElement;
                            if (hae != null) hae.click();
                        }
                    }
                }
            }
        }
 
        /// <summary>
        /// 反回页面元素
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="AttName"></param>
        /// <param name="AttValue"></param>
        /// <param name="innerHtml"></param>
        /// <param name="listOfHtmlControls"></param>
        /// <returns></returns>
        public static HtmlElement FindControlByAttValue(this WebBrowser webBrowser, string Tag, string AttName, string AttValue, string innerText, HtmlElementCollection listOfHtmlControls)
        {
            try
            {
                foreach (HtmlElement element in listOfHtmlControls)
                {
                    if (!string.IsNullOrEmpty(element.OuterHtml))
                    {
                        if (element.TagName.ToLower() == Tag.ToLower())
                        {
                            string OuterHtml = element.OuterHtml;
                            if (OuterHtml == null) continue;
                            OuterHtml = OuterHtml.Substring(0, OuterHtml.IndexOf(">"));
                            OuterHtml = OuterHtml.ToLower();
 
                            if (OuterHtml.Contains(AttName.ToLower()) && OuterHtml.Contains(AttValue.ToLower()))
                            {
                                string e = element.InnerText;
                                if (e == null) e = "";
                                if (e.Trim().ToLower().Contains(innerText.ToLower()))
                                {
                                    return element;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            return null;
        }
 
        /// <summary>
        /// 根据ID反回页面元素
        /// </summary>
        /// <param name="id"></param>
        /// <param name="listOfHtmlControls"></param>
        /// <returns></returns>
        private static HtmlElement FindControlById(this WebBrowser webBrowser, string id, HtmlElementCollection listOfHtmlControls)
        {
            if (listOfHtmlControls == null)
            {
                return null;
            }
 
            foreach (HtmlElement element in listOfHtmlControls)
            {
                if (element.Id == id)
                {
                    return element;
                }
            }
            return null;
        }
        #endregion
 
        #region   UserAgent
 
        private static string defaultUserAgent = null;
        [DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
        private static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
        const int URLMON_OPTION_USERAGENT = 0x10000001;
 
        /// <summary>
        /// 在默认的UserAgent后面加一部分
        /// </summary>
        public static void AppendUserAgent(this WebBrowser web, string appendUserAgent)
        {
            if (web.InvokeRequired)
            {
                IAsyncResult ir = web.BeginInvoke(new Action(() => AppendUserAgent(web, appendUserAgent)));
                web.EndInvoke(ir);
            }
            else
            {
                if (string.IsNullOrEmpty(defaultUserAgent))
                {
                    defaultUserAgent = GetDefaultUserAgent();
                }
                string ua = defaultUserAgent   ";"   appendUserAgent;
                SetUserAgent(web, ua);
            }
        }
        /// <summary>
        /// 修改UserAgent
        /// </summary>
        public static void SetUserAgent(this WebBrowser webBrowser, string userAgent)
        {
            if (webBrowser.InvokeRequired)
            {
                IAsyncResult ir = webBrowser.BeginInvoke(new Action(() => SetUserAgent(webBrowser, userAgent)));
                webBrowser.EndInvoke(ir);
            }
            else
            {
                UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, userAgent, userAgent.Length, 0);
            }
        }
        /// <summary>
        /// 一个很BT的获取IE默认UserAgent的方法
        /// </summary>
        private static string GetDefaultUserAgent()
        {
            WebBrowser wb = new WebBrowser();
            wb.Navigate("about:blank");
            while (wb.IsBusy) Application.DoEvents();
            object window = wb.Document.Window.DomWindow;
            Type wt = window.GetType();
            object navigator = wt.InvokeMember("navigator", BindingFlags.GetProperty,
                null, window, new object[] { });
            Type nt = navigator.GetType();
            object userAgent = nt.InvokeMember("userAgent", BindingFlags.GetProperty,
                null, navigator, new object[] { });
            return userAgent.ToString();
        }
 
        #endregion
 
        #region  cookie相关
        /// <summary>
        /// 清除cookie
        /// </summary>
        public static void ClearCookie(this WebBrowser webBrowser)
        {
            if (webBrowser.InvokeRequired)
            {
                IAsyncResult ir = webBrowser.BeginInvoke(new Action(() => ClearCookie(webBrowser)));
                webBrowser.EndInvoke(ir);
            }
            else
            {
                webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e  ){f  ;for(b='.' location.host;b;b=b.replace(/^(?:%5C.|[^%5C.] )/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e] '; domain=' b '; path=' c '; expires=' new Date((new Date()).getTime()-1e11).toGMTString());}}}})())");
            }
        }
 
        #endregion
 
        #region 滚动条
 
        /// <summary>
        /// 滚动条
        /// </summary>
        public static void ScrollTo(this WebBrowser webBrowser1)
        {
            if (webBrowser1.InvokeRequired)
            {
                webBrowser1.BeginInvoke(new Action(() => ScrollTo(webBrowser1)));
            }
            else
            {
                HtmlDocument document = webBrowser1.Document;
                if (document != null && document.Window != null && webBrowser1.Document != null &&
                    webBrowser1.Document.Body != null)
                {
                    document.Window.ScrollTo(0, webBrowser1.Document.Body.ScrollRectangle.Height);
                }
            }
        }
 
        #endregion
 
    }
}


标签: IP 代理 http C# c

实例下载地址

C# 模拟http 发包请求工具源码(可设置代理IP)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

第 1 楼 liuhuang1205 发表于: 2017-06-29 18:58 04
写的不错,正好符合我需要的

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有1条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警