【问题标题】:How to get source code after simulate web page button click in code如何在代码中模拟网页按钮点击后获取源代码
【发布时间】:2013-07-17 09:20:45
【问题描述】:

我正在尝试获取单击按钮后获得的网页源代码。

我可以点击网页上的按钮。

 webBrowser1.Navigate(url);
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
    Application.DoEvents();
}               
webBrowser1.Document.GetElementById("downloadButton").InvokeMember("click");

在此之后会出现一个新窗口。这样点击后是否可以得到这个新窗口的源代码。

【问题讨论】:

    标签: c# .net button click


    【解决方案1】:

    hacky 方法是:

    1. 将事件处理程序附加到按钮的“onclick”事件。
    2. 然后,一旦触发事件,使用 Microsoft Internet Controls (SHDocVw) 类型库以获取在 IE 中打开的最后一个 URL。
    3. 最后,导航到 URL,加载文档后,从 webBrowser1.DocumentText 属性获取文档的源。

    在您的项目中,添加对 Microsoft Internet Controls 类型库的引用(您可以在 COM 选项卡中找到它)。在文件顶部添加:

    using SHDocVw;
    

    代码:

    webBrowser1.Navigate(url);
    while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
    {
        Application.DoEvents();
    }
    
    // assign the button to a variable
    var button = webBrowser1.Document.GetElementById("downloadButton");
    
    // attach an event handler for the 'onclick' event of the button
    button.AttachEventHandler("onclick", (a, b) =>
    {
        // use the Microsoft Internet Controls COM library
        var shellWindows = new SHDocVw.ShellWindows();
    
        // get the location of the last window in the collection
        var newLocation = shellWindows.Cast<SHDocVw.InternetExplorer>()
            .Last().LocationURL;
    
        // navigate to the newLocation
        webBrowser1.Navigate(newLocation);
        while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
        {
            Application.DoEvents();
        }
    
        // get the document's source
        var source = webBrowser1.DocumentText;
    });
    
    button.InvokeMember("click");
    

    【讨论】:

    • 运行上述代码时出现脚本错误。说:!此页面上的脚本发生错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    相关资源
    最近更新 更多