在标记中找到javascript并确定它是否位于标题标签上方的正确方法是什么?

What is the right way to find javascript in mark up and determine whether or not it lies above the title tag?

本文关键字:标签 标题 是什么 方法 javascript 是否 于标题      更新时间:2023-09-26

我需要看看html页面标记是否在源代码中包含谷歌分析,在脚本块中,并且脚本块在<title>标记之上。

我已经设法把网页的源代码变成一个变量。

我正在努力写正确的正则表达式拉出代码的谷歌分析部分知道是否首先它是存在的,其次,javascript是在标签之前!

有什么建议吗?

避免使用正则表达式解析html;陷阱太多了。假设您在文档中搜索字符串"<title"。如果找不到"><TITLE"怎么办?很容易进行不区分大小写的匹配。但是…如果在注释中嵌入了"><title"字符串怎么办?如果在脚本块中嵌入了这样一个字符串怎么办?等等等等。>

任何HTML文档的"搜索"需要做的不仅仅是简单的文本搜索。它需要具有文档意识。这就是htmllagilitypack提供的。可以免费下载。

像这样开始:

using HtmlAgilityPack; 
   ....
    HtmlDocument doc = new HtmlDocument();
    doc.Load(fileName);
    var titles = doc.DocumentNode.SelectNodes("/html/head/title");
    if (titles != null)
    {
        foreach(var title in titles)
        {
            Console.WriteLine("<title> on line: " + title.Line);
        }
        var scripts = doc.DocumentNode.SelectNodes("/html/head/script");
        if (scripts != null)
        {
            foreach(var script in scripts)
            {
                Console.WriteLine("<script> on line: " + script.Line);
                // here, you need to decide if the script is before the title
                // and if it is the "right" script - google analytics. 
                // you have to do that part yourself.
            }
        }
        else
        {
            Console.WriteLine("No script nodes found.");
        }
    }
    else
    {
        Console.WriteLine("No title node found.");
    }