c# - 如何只从网站上删除 <body> 标签

标签 c# .net html-parsing web-scraping

我正在研究网络爬虫。目前我抓取了全部内容,然后使用正则表达式删除了 <meta>, <script>, <style>和其他标签并获取正文的内容。

但是,我正在尝试优化性能,我想知道是否有一种方法可以只抓取 <body>页面的?

namespace WebScraper
{
    public static class KrioScraper
    {    
        public static string scrapeIt(string siteToScrape)
        {
            string HTML = getHTML(siteToScrape);
            string text = stripCode(HTML);
            return text;
        }

        public static string getHTML(string siteToScrape)
        {
            string response = "";
            HttpWebResponse objResponse;
            HttpWebRequest objRequest = 
                (HttpWebRequest) WebRequest.Create(siteToScrape);
            objRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; " +
                "Windows NT 5.1; .NET CLR 1.0.3705)";
            objResponse = (HttpWebResponse) objRequest.GetResponse();
            using (StreamReader sr =
                new StreamReader(objResponse.GetResponseStream()))
            {
                response = sr.ReadToEnd();
                sr.Close();
            }
            return response;
        }

        public static string stripCode(string the_html)
        {
            // Remove google analytics code and other JS
            the_html = Regex.Replace(the_html, "<script.*?</script>", "", 
                RegexOptions.Singleline | RegexOptions.IgnoreCase);
            // Remove inline stylesheets
            the_html = Regex.Replace(the_html, "<style.*?</style>", "", 
                RegexOptions.Singleline | RegexOptions.IgnoreCase);
            // Remove HTML tags
            the_html = Regex.Replace(the_html, "</?[a-z][a-z0-9]*[^<>]*>", "");
            // Remove HTML comments
            the_html = Regex.Replace(the_html, "<!--(.|\\s)*?-->", "");
            // Remove Doctype
            the_html = Regex.Replace(the_html, "<!(.|\\s)*?>", "");
            // Remove excessive whitespace
            the_html = Regex.Replace(the_html, "[\t\r\n]", " ");

            return the_html;
        }
    }
}

来自 Page_Load我调用scrapeIt()方法将我从页面的文本框中获取的字符串传递给它。

最佳答案

仍然是最简单/最快(最不准确)的方法。

int start = response.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
int end = response.LastIndexOf("</body>", StringComparison.CurrentCultureIgnoreCase);
return response.Substring(start, end-start + "</body>".Length);

显然,如果 HEAD 标记中有 javascript,例如...

document.write("<body>");

然后你会得到比你想要的多一点。

关于c# - 如何只从网站上删除 <body> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7082649/

相关文章:

parsing - 从 HTML 文件中获取 jpg 图像

go - 在 GoLang 中解析来自维基百科的 S&P 500 数据

c# - AngleSharp Html Parser 线程安全吗?

c# - 编写一个不是容器的泛型类? [C#]

c# - 如何将 DateTimePicker 值设置为今天的日期+1

c# - 用于将 3 个主节点连接到 MySQL 的 ConnectionString

c# - 可空值类型只是常规值类型的包装器吗?

c# - 在字符串的二进制搜索中应用索引

c# - 将这种字符串解析为 DateTime - "Friday 22nd March 2013"(C#)

c# - 属性/访问器的 XML 注释