搜索引擎如何抓取网页(从Web网页提取文本之前,首先要识别网页的编码 )
优采云 发布时间: 2022-02-10 21:27搜索引擎如何抓取网页(从Web网页提取文本之前,首先要识别网页的编码
)
在从网页中提取文本之前,首先要确定页面的编码,如果需要,还要确定页面的语言。整体流程如下:
1. 从 Web 服务器返回的内容类型中提取代码。如果编码为gb2312,则应视为GBK。
2. 从网页的 Meta 信息中识别字符编码。如果与内容类型中的编码不一致,以Meta中声明的编码为准。
3. 如果还是不能确定网页使用的字符集,需要从返回流的二进制格式来判断。同时,需要确定网页使用的语言。例如,UTF-8编码的语言可以是中文、英文、日文、韩文等任意语言。
单词。 “自己动手做的搜索引擎”
以下是从新浪网下载的源代码
新闻中心首页_新浪网
常见的 HTML 解析器是 HtmlParser 和 JSoup。和.Net平台下的Winista.Htmlparser.Net
html解析可以参考
html解析器
使用HtmlParser.Net从meta中获取编码信息
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Winista.Text.HtmlParser;
using Winista.Text.HtmlParser.Lex;
using Winista.Text.HtmlParser.Util;
using Winista.Text.HtmlParser.Tags;
using Winista.Text.HtmlParser.Filters;
namespace OpenSearchEngine
{
public class HtmlParser
{
public static String GetCharset(String content)
{
const String CHARSET_STRING = "charset";
int index;
String ret;
ret = null;
if (null != content)
{
index = content.IndexOf(CHARSET_STRING);
if (index != -1)
{
content = content.Substring(index + CHARSET_STRING.Length).Trim();
if (content.StartsWith("="))
{
content = content.Substring(1).Trim();
index = content.IndexOf(";");
if (index != -1)
content = content.Substring(0, index);//remove any double quotes from around charset string
if (content.StartsWith("\"") && content.EndsWith("\"") && (1 < content.Length))
content = content.Substring(1, content.Length - 1);
//remove any single quote from around charset string
if (content.StartsWith("'") && content.EndsWith("'") && (1 < content.Length))
content = content.Substring(1, content.Length - 1);
ret = content;
}
}
}
return (ret);
}
///
/// 利用HtmlParser.Net得到编码
///
///
///
public static String GetCharsetFromMeta(string content)
{
string result = "";
Lexer lexer = new Lexer(content);//Lexer包含了词法分析的代码;
Parser parser = new Parser(lexer);//解析器
NodeFilter filter = new NodeClassFilter(typeof(Winista.Text.HtmlParser.Tags.MetaTag));//节点过滤器
NodeList htmlNodes = parser.Parse(filter);//使用节点过滤得到NodeList
/* 解析之后,我们可以采用:
* INode[] nodes = nodeList.toNodeArray();
* 来获取节点数组,也可以直接访问:
* INode node = nodeList.elementAt(i);
* 来获取Node。
* 另外,在Filter后得到NodeList以后,我们仍然可以使用
* nodeList.extractAllNodesThatMatch(someFilter)
* 来进一步过滤,同时又可以用
* nodeList.visitAllNodesWith(someVisitor)来做进一步的访问。
*/
for (int i = 0; i < htmlNodes.Count; i++)
{
ITag tag = htmlNodes[i] as ITag;
if (tag != null)
{
string charset = GetCharset(tag.GetAttribute("content"));
if (!string.IsNullOrEmpty(charset))
return charset;
}
}
return result;
}
private static ITag getTag(INode node)
{
if (node == null)
return null;
return node is ITag ? node as ITag : null;
}
}
}
string path = @"D:\Docs\Test.htm";
string content = System.IO.File.ReadAllText(path);
tbShow.Text = OpenSearchEngine.HtmlParser.GetCharsetFromMeta(content);