栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

C#WebBrowser控件-表单提交无法使用InvokeMember(“点击”)进行

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#WebBrowser控件-表单提交无法使用InvokeMember(“点击”)进行

以下代码对我有用,它使用问题注释中的实时表单操作URL(已通过IE10测试)。按原样尝试。如果它也适合您,请随时将其用作Web自动化任务的模板。要点:

  • FEATURE_BROWSER_EMULATION用于确保

    WebBrowser
    行为与独立IE浏览器相同(或尽可能接近)。 对于几乎所有
    WebBrowser
    基于项目的项目 都是必须 的。我相信这应该有助于解决您这一方面的原始问题。

  • 异步代码用于提高自动化逻辑的可靠性,增加支持超时和取消并促进自然的线性代码流(使用

    async/await
    )。

C#

using Microsoft.Win32;using System;using System.Diagnostics;using System.Linq;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;namespace WebAutomation{    // http://stackoverflow.com/q/19044659/1768303    public partial class MainForm : Form    {        WebBrowser webBrowser;        // non-deterministic delay to let AJAX pre run        const int AJAX_DELAY = 1000;        // keep track of the main automation task        CancellationTokenSource mainCts;        Task mainTask = null;        public MainForm()        { SetBrowserFeatureControl(); // set FEATURE_BROWSER_EMULATION first InitializeComponent(); InitBrowser(); this.Load += (s, e) => {     // start the automation when form is loaded     // timeout the whole automation task in 30s     mainCts = new CancellationTokenSource(30000);     mainTask = DoAutomationAsync(mainCts.Token).ContinueWith((completedTask) =>     {         Trace.WriteLine(String.Format("Automation task status: {0}", completedTask.Status.ToString()));     }, TaskScheduler.FromCurrentSynchronizationContext()); }; this.FormClosing += (s, e) => {     // cancel the automation if form closes     if (this.mainTask != null && !this.mainTask.IsCompleted)         mainCts.Cancel(); };        }        // create a WebBrowser instance (could use an existing one)        void InitBrowser()        { this.webBrowser = new WebBrowser(); this.webBrowser.Dock = DockStyle.Fill; this.Controls.Add(this.webBrowser); this.webBrowser.Visible = true;        }        // the main automation logic        async Task DoAutomationAsync(CancellationToken ct)        { await NavigateAsync(ct, () => this.webBrowser.Navigate("http://localhost:81/test.html"), 10000); // timeout in 10s // page loaded, log the page's HTML Trace.WriteLine(GetBrowserdocumentHtml()); // do the DOM automation HtmlElementCollection all = webBrowser.document.GetElementsByTagName("button"); // throw if none or more than one element found HtmlElement btn = all.Cast<HtmlElement>().Single(     el => el.InnerHtml == "ACCEPT the terms of use"); ct.ThrowIfCancellationRequested(); // simulate a click which causes navigation await NavigateAsync(ct, () => btn.InvokeMember("click"), 10000); // timeout in 10s // form submitted and new page loaded, log the page's HTML Trace.WriteLine(GetBrowserdocumentHtml()); // could continue with another NavigateAsync // othrwise, the automation session completed        }        // Get the full HTML content of the document        string GetBrowserdocumentHtml()        { return this.webBrowser.document.GetElementsByTagName("html")[0].OuterHtml;        }        // Async navigation        async Task NavigateAsync(CancellationToken ct, Action startNavigation, int timeout = Timeout.Infinite)        { var onloadTcs = new TaskCompletionSource<bool>(); EventHandler onloadEventHandler = null; WebBrowserdocumentCompletedEventHandler documentCompletedHandler = delegate {     // documentCompleted may be called several time for the same page,     // beacuse of frames     if (onloadEventHandler != null || onloadTcs == null || onloadTcs.Task.IsCompleted)         return;     // handle DOM onload event to make sure the document is fully loaded     onloadEventHandler = (s, e) =>         onloadTcs.TrySetResult(true);     this.webBrowser.document.Window.AttachEventHandler("onload", onloadEventHandler); }; using (var cts = CancellationTokenSource.CreatelinkedTokenSource(ct)) {     if (timeout != Timeout.Infinite)         cts.CancelAfter(Timeout.Infinite);     using (cts.Token.Register(() => onloadTcs.TrySetCanceled(), useSynchronizationContext: true))      {         this.webBrowser.documentCompleted += documentCompletedHandler;         try          {  startNavigation();  // wait for DOM onload, throw if cancelled  await onloadTcs.Task;  ct.ThrowIfCancellationRequested();  // let AJAX pre run, throw if cancelled  await Task.Delay(AJAX_DELAY, ct);         }         finally          {  this.webBrowser.documentCompleted -= documentCompletedHandler;  if (onloadEventHandler != null)      this.webBrowser.document.Window.DetachEventHandler("onload", onloadEventHandler);         }     } }        }        // Browser feature conntrol        void SetBrowserFeatureControl()        { // http://msdn.microsoft.com/en-us/library/ee330720(v=vs.85).aspx // FeatureControl settings are per-process var fileName = System.IO.Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName); // make the control is not running inside Visual Studio Designer if (String.Compare(fileName, "devenv.exe", true) == 0 || String.Compare(fileName, "XDesProc.exe", true) == 0)     return; SetBrowserFeatureControlKey("FEATURE_BROWSER_EMULATION", fileName, GetBrowserEmulationMode()); // Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.        }        void SetBrowserFeatureControlKey(string feature, string appName, uint value)        { using (var key = Registry.CurrentUser.CreateSubKey(     String.Concat(@"SoftwareMicrosoftInternet ExplorerMainFeatureControl", feature),     RegistryKeyPermissionCheck.ReadWriteSubTree)) {     key.SetValue(appName, (UInt32)value, RegistryValueKind.DWord); }        }        UInt32 GetBrowserEmulationMode()        { int browserVersion = 7; using (var ieKey = Registry.LocalMachine.OpenSubKey(@"SOFTWAREMicrosoftInternet Explorer",     RegistryKeyPermissionCheck.ReadSubTree,     System.Security.AccessControl.RegistryRights.QueryValues)) {     var version = ieKey.GetValue("svcVersion");     if (null == version)     {         version = ieKey.GetValue("Version");         if (null == version)  throw new ApplicationException("Microsoft Internet Explorer is required!");     }     int.TryParse(version.ToString().Split('.')[0], out browserVersion); } UInt32 mode = 10000; // Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10. switch (browserVersion) {     case 7:         mode = 7000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control.         break;     case 8:         mode = 8000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8         break;     case 9:         mode = 9000; // Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.         break;     default:         // use IE10 mode by default         break; } return mode;        }    }}

内容

http://localhost:81/test.html

<!DOCTYPE html><head><meta http-equiv="X-UA-Compatible" content="IE=edge"/></head><body>    <form action="<the URL from OP's comments>" method="post">        <input name="StepCheck" value="U2FsdGVkX18zMTk5MzE5OUgFyFgD3V5yf5Rwbtfhf3gjdH4KSx4hqj4vkrw7K6e-" type="hidden">        <button type="submit" name="continue" value="y">ACCEPT the terms of use</button>        <button type="submit" name="continue" value="n">DECLINE the terms of use</button>    </form></body>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/433068.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号