2

有没有办法从 C# 打开 Internet Explorer 进程,将 html 内容发送到这个浏览器并捕获“显示”的内容?

我知道其他 html 剥离方法(例如 HtmlAgilityPack),但我想探索上述途径。

谢谢, LG

4

2 回答 2

3

您可以使用 WinForms 和 WPF 都存在的 WebBrowser 控件在您的应用程序中托管 IE。然后您可以将控件的 Source 设置为您的 HTML,等待内容加载(使用 LayoutUpdated 事件,而不是在 HTML 下载完成时引发的 Loaded 事件,不一定安排好所有动态 JS 运行),然后访问Document 属性来获取 HTML。

于 2012-02-19T14:52:10.630 回答
0
    public List<LinkItem> getListOfLinksFromPage(string webpage)
    {
        WebClient w = new WebClient();
        List<LinkItem> list = new List<LinkItem>();
        try
        {
            string s = w.DownloadString(webpage);

            foreach (LinkItem i in LinkFinder.Find(s))
            {
                //Debug.WriteLine(i);
                //richTextBox1.AppendText(i.ToString() + "\n");
                list.Add(i);
            }
            listTest = list;
            return list;
        }
        catch (Exception e)
        {
            return list;
        }

    }

    public struct LinkItem
    {
        public string Href;
        public string Text;

        public override string ToString()
        {
            return Href;
        }
    }

    static class LinkFinder
    {
        public static List<LinkItem> Find(string file)
        {
            List<LinkItem> list = new List<LinkItem>();

            // 1.
            // Find all matches in file.
            MatchCollection m1 = Regex.Matches(file, @"(<a.*?>.*?</a>)", RegexOptions.Singleline);

            // 2.
            // Loop over each match.
            foreach (Match m in m1)
            {
                string value = m.Groups[1].Value;
                LinkItem i = new LinkItem();

                // 3.
                // Get href attribute.
                Match m2 = Regex.Match(value, @"href=\""(.*?)\""",
                RegexOptions.Singleline);
                if (m2.Success)
                {
                    i.Href = m2.Groups[1].Value;
                }

                // 4.
                // Remove inner tags from text.
                string t = Regex.Replace(value, @"\s*<.*?>\s*", "",
                RegexOptions.Singleline);
                i.Text = t;

                list.Add(i);
            }

            return list;

        }
    }

其他人创建了正则表达式,所以我不能相信,但上面的代码将打开一个 webclient 对象到传入的网页,并使用正则表达式来查找该页面的所有 childLinks。不确定这是否是您要查找的内容,但如果您只是想“抓取”所有 HTML 内容并将其保存到文件中,您可以简单地保存在“string s = w”行中创建的字符串“s” .DownloadString(网页);" 到一个文件。

于 2012-02-19T18:08:26.147 回答