创建一个使用 WebBrowser 并返回 HTML 的方法



如何创建一个这样做的方法:
登录到网站,然后阅读(仅限会员(页面并返回 HTML。

我想出了这个(这显然不起作用,因为我不知道如何让它返回页面内容(

public string LoginAndReadPage() {
    WebBrowser wb = new WebBrowser();
    wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
    wb.Navigate("hxxp://mysite.com/login");
}
private async void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    if (wb.Url.ToString().Contains("login"))
    {
        wb.Document.GetElementsByTagName("input").GetElementsByName("email")[0].SetAttribute("value", _login);
        wb.Document.GetElementsByTagName("input").GetElementsByName("password")[0].SetAttribute("value", _password);
        wb.Document.GetElementsByTagName("button")[0].InvokeMember("click");
    }
    else if (wb.Url.ToString().Contains("dashboard"))
    {
        return wb.DocumentText; // I want to return the content of mysite.com/dashboard
    }
    else
    {
        await Task.Delay(1000); //wait for 1 second just to let the WB catch up
        wb.Navigate("hxxp://mysite.com/dashboard");
    }
}

提前致谢

您要做的称为"抓取"或有时称为"网络抓取"。这是一个很大的话题,所以我建议谷歌搜索它。

您可能也可以通过 C# 驱动程序使用类似 Selenium 的东西来执行此操作。Selenium是为自动化UI测试而设计的,但它绝对拥有做你想做的事所需的所有工具。

最新更新