如何在模拟网页按钮点击代码后获取源代码

时间:2013-07-17 09:20:46

标签: c# .net button click

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

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

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

此后会出现一个新窗口。这可以在单击后显示此新窗口的源代码。

1 个答案:

答案 0 :(得分:0)

hacky 方法是:

  1. 将事件处理程序附加到按钮的“onclick”事件。
  2. 然后,触发事件后,使用 Microsoft Internet Controls(SHDocVw)类型库,以便在IE中打开最后一个URL。
  3. 最后,导航到URL,加载文档后,从webBrowser1.DocumentText属性获取文档的来源。
  4. 在您的项目中,添加对 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");
    
相关问题